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();}
}
注意事项
-
安全性:FTP 协议本身不加密,考虑使用 FTPS (FTP over SSL) 或 SFTP (SSH File Transfer Protocol) 进行安全传输。
-
异步操作:长时间运行的 FTP 操作应该使用异步方法,避免阻塞 UI 线程。
-
错误处理:妥善处理网络连接问题、权限问题等异常情况。
-
进度显示:对于大文件传输,可以实现进度显示功能。
-
连接管理:合理管理 FTP 连接,及时关闭不再使用的连接。
以上代码提供了基本的 FTP 功能实现,你可以根据实际需求进行调整和扩展。