当前位置: 首页 > news >正文

C# winform FTP功能

C# WinForms FTP 功能实现

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

基本 FTP 操作实现

1. 添加必要的命名空间

using System.IO;
using System.Net;
using System.Text;

2. FTP 文件上传

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 文件下载

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 目录内容

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 功能:

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

使用示例

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

http://www.dtcms.com/a/338551.html

相关文章:

  • openldap安装 -添加条目
  • 项目管理.管理理念学习
  • 跟踪不稳定目标:基于外观引导的运动建模实现无人机视频中的鲁棒多目标跟踪
  • 第10章 React应用测试
  • 一、快速掌握python中的序列、集合和字典的用法(数据容器)
  • RxJava 在 Android 即时通讯中的应用:封装、处理与控制
  • 《WASM驱动本地PDF与Excel预览组件的深度实践》
  • 达梦数据库表恢复方法总结
  • 章11:管理网络
  • 网络基础——网络传输基本流程
  • Android Coil 3拦截器Interceptor计算单次请求耗时,Kotlin
  • GPT-4.1旗舰模型:复杂任务的最佳选择及API集成实践
  • 基于prompt的生物信息学:多组学分析的新界面
  • RecSys:粗排模型和精排特征体系
  • 力扣57:插入区间
  • Apache IoTDB:大数据时代时序数据库选型的技术突围与实践指南
  • 【力扣 Hot100】 刷题日记——双指针的经典应用
  • 论文阅读:Prompt Optimization in Large Language Models
  • @Linux问题 :bash fork Cannot allocate memory 错误分析与解决方案
  • Spring Boot 使用 单元测试(JUnit )教程
  • 【LeetCode题解】LeetCode 162. 寻找峰值
  • 什么是矩阵系统源码搭建定制化开发,支持OEM贴牌
  • AndroidR车机系统Settings数据库增加非持久化存储键值方案-续
  • 快手可灵招海外产品运营实习生
  • vue,H5车牌弹框定制键盘包括新能源车牌
  • word如何转换为pdf
  • 网络基础——Socket编程预备
  • 专题:2025母婴行业消费洞察与分龄营养趋势报告|附40 +份报告PDF、交互图表数据汇总下载
  • MongoDB知识速查
  • uni-app页面使用u-view组件简化版列表页+详情页实现