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 功能实现,你可以根据实际需求进行调整和扩展。

相关推荐
小草儿7997 小时前
gbase8s之.net8连接8s之mysql模式(windows)demo
windows·mysql·.net
梵得儿SHI7 小时前
Java 注解与反射实战:自定义注解从入门到精通
java·开发语言·注解·自定义注解·元注解·控制注解的作用·声明式编程思想
沐知全栈开发8 小时前
Foundation 网格实例
开发语言
专注前端30年8 小时前
【JavaScript】every 方法的详解与实战
开发语言·前端·javascript
速易达网络8 小时前
Java Web登录系统实现(不使用开发工具)
java·开发语言·前端
唐青枫8 小时前
C#.NET Configuration 全面解析:从多环境到强类型绑定实战
c#·.net
凡间客8 小时前
Python编程之常用模块
开发语言·python
景彡先生8 小时前
Python基础语法规范详解:缩进、注释与代码可读性
开发语言·前端·python
悟能不能悟8 小时前
java重构旧代码有哪些注意的点
java·开发语言·重构
歪歪1008 小时前
如何在Qt中使用VS的调试功能
运维·开发语言·网络·qt·网络协议·visual studio