C# winform FTP功能

C# WinForms FTP 功能实现

在 C# WinForms 应用程序中实现 FTP 功能可以通过 .NET 提供的 FtpWebRequest 类或第三方库来完成。下面我将介绍几种常见的 FTP 操作实现方法。

基本 FTP 操作实现

1. 添加必要的命名空间

csharp 复制代码
using System.IO;
using System.Net;
using System.Text;

2. FTP 文件上传

csharp 复制代码
public bool UploadFileToFtp(string localFilePath, string ftpServerUrl, string ftpUsername, string ftpPassword)
{
    try
    {
        // 创建 FTP 请求
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerUrl);
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
        
        // 读取本地文件
        byte[] fileContents;
        using (StreamReader sourceStream = new StreamReader(localFilePath))
        {
            fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        }

        // 上传文件
        request.ContentLength = fileContents.Length;
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileContents, 0, fileContents.Length);
        }

        // 获取响应
        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
            Console.WriteLine($"Upload File Complete, status {response.StatusDescription}");
            return true;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"上传文件失败: {ex.Message}");
        return false;
    }
}

3. FTP 文件下载

csharp 复制代码
public bool DownloadFileFromFtp(string localFilePath, string ftpServerUrl, string ftpUsername, string ftpPassword)
{
    try
    {
        // 创建 FTP 请求
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerUrl);
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

        // 获取响应并保存文件
        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        using (Stream responseStream = response.GetResponseStream())
        using (StreamWriter writer = new StreamWriter(localFilePath))
        {
            writer.Write(new StreamReader(responseStream).ReadToEnd());
            Console.WriteLine($"Download Complete, status {response.StatusDescription}");
            return true;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"下载文件失败: {ex.Message}");
        return false;
    }
}

4. 列出 FTP 目录内容

csharp 复制代码
public List<string> ListFtpDirectory(string ftpServerUrl, string ftpUsername, string ftpPassword)
{
    List<string> files = new List<string>();
    
    try
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerUrl);
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        using (Stream responseStream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(responseStream))
        {
            string line = reader.ReadLine();
            while (line != null)
            {
                files.Add(line);
                line = reader.ReadLine();
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"列出目录失败: {ex.Message}");
    }

    return files;
}

WinForms 界面示例

下面是一个简单的 WinForms 界面示例,包含 FTP 功能:

csharp 复制代码
public partial class FtpForm : Form
{
    private string ftpServer = "ftp://example.com/";
    private string username = "your_username";
    private string password = "your_password";

    public FtpForm()
    {
        InitializeComponent();
    }

    private void btnUpload_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            string remotePath = ftpServer + Path.GetFileName(openFileDialog.FileName);
            if (UploadFileToFtp(openFileDialog.FileName, remotePath, username, password))
            {
                MessageBox.Show("上传成功!");
            }
        }
    }

    private void btnDownload_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog = new SaveFileDialog();
        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            string remotePath = ftpServer + Path.GetFileName(saveFileDialog.FileName);
            if (DownloadFileFromFtp(saveFileDialog.FileName, remotePath, username, password))
            {
                MessageBox.Show("下载成功!");
            }
        }
    }

    private void btnListDirectory_Click(object sender, EventArgs e)
    {
        List<string> files = ListFtpDirectory(ftpServer, username, password);
        listBoxFiles.Items.Clear();
        foreach (string file in files)
        {
            listBoxFiles.Items.Add(file);
        }
    }
}

使用 FluentFTP 第三方库

对于更复杂的 FTP 操作,推荐使用 FluentFTP 库,它提供了更简单易用的 API。

安装 FluentFTP

通过 NuGet 包管理器安装:

复制代码
Install-Package FluentFTP

使用示例

csharp 复制代码
using FluentFTP;

public class FtpHelper
{
    private FtpClient client;

    public FtpHelper(string host, string username, string password)
    {
        client = new FtpClient(host, username, password);
    }

    public void Connect()
    {
        client.Connect();
    }

    public void Disconnect()
    {
        client.Disconnect();
    }

    public bool UploadFile(string localPath, string remotePath)
    {
        try
        {
            return client.UploadFile(localPath, remotePath);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"上传失败: {ex.Message}");
            return false;
        }
    }

    public bool DownloadFile(string localPath, string remotePath)
    {
        try
        {
            return client.DownloadFile(localPath, remotePath);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"下载失败: {ex.Message}");
            return false;
        }
    }

    public List<string> GetFileList(string directory = "/")
    {
        return client.GetListing(directory).Select(item => item.Name).ToList();
    }
}

注意事项

  1. 安全性:FTP 协议本身不加密,考虑使用 FTPS (FTP over SSL) 或 SFTP (SSH File Transfer Protocol) 进行安全传输。

  2. 异步操作:长时间运行的 FTP 操作应该使用异步方法,避免阻塞 UI 线程。

  3. 错误处理:妥善处理网络连接问题、权限问题等异常情况。

  4. 进度显示:对于大文件传输,可以实现进度显示功能。

  5. 连接管理:合理管理 FTP 连接,及时关闭不再使用的连接。

以上代码提供了基本的 FTP 功能实现,你可以根据实际需求进行调整和扩展。

相关推荐
-Xie-9 分钟前
Maven(二)
java·开发语言·maven
mftang11 分钟前
Python可视化工具-Bokeh:动态显示数据
开发语言·python
m0_4805026421 分钟前
Rust 入门 生命周期-next2 (十九)
开发语言·后端·rust
IT利刃出鞘21 分钟前
Java线程的6种状态和JVM状态打印
java·开发语言·jvm
有梦想的攻城狮2 小时前
Java 11中的Collections类详解
java·windows·python·java11·collections
minji...2 小时前
C++ string类(STL简介 , string类 , 访问修改字符)
开发语言·c++
Forward♞2 小时前
Qt——文件操作
开发语言·c++·qt
十五年专注C++开发3 小时前
CMake进阶: CMake Modules---简化CMake配置的利器
linux·c++·windows·cmake·自动化构建