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

相关推荐
牛奔8 小时前
Go 如何打印调试深层或嵌套的结构体
开发语言·后端·golang
geovindu9 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
学逆向的9 小时前
汇编——JCC指令
开发语言·汇编·网络安全
像风一样自由20209 小时前
从本地到公网:Windows 下使用 Cloudflare Quick Tunnel 与 Natapp 联调 FastAPI
windows·fastapi
mayaairi10 小时前
JS循环语句深度解析:嵌套for、while与do...while
开发语言·前端·javascript
kite012110 小时前
Go语言Map深度解析与最佳实践
开发语言·后端·golang
l1564694812 小时前
突围!图文混合知识库难以解析,Kimi-K3 原生视觉架构深耕知识工作,DMXAPI 统一接口,缩短项目开发周期
java·大数据·开发语言
charlie11451419112 小时前
现代C++工程实践 WeakPtr 实战(三):WeakPtrFactory 与「最后成员」惯用法
开发语言·c++·开源项目·现代c++
吴可可12313 小时前
C#用OpenCVSharp提取轮廓生成CAD多段线
c#
IT小盘13 小时前
04-大模型流式输出原理-SSE与Python实现
开发语言·网络·人工智能·python