编辑
2025-02-03
C# 应用
00
请注意,本文编写于 92 天前,最后修改于 92 天前,其中某些信息可能已经过时。

目录

技术特点
服务端
实现FTP客户端
上传文件
下载文件
列表服务器文件
注意事项

FTP(File Transfer Protocol,文件传输协议)是一种用于在客户端和服务器之间传输文件的标准网络协议。使用C#编程语言,我们可以轻松实现一个FTP客户端。本文将探讨如何实现基本的FTP功能,包括连接FTP服务器、上传和下载文件。

技术特点

  1. 易于使用:C#提供了FtpWebRequest类,使得FTP操作如上传、下载变得非常容易。
  2. 功能全面:支持多种FTP操作,包括上传、下载、删除、列目录等。
  3. 可扩展性强:可以轻松扩展以满足特定的业务需求。

服务端

image.png

实现FTP客户端

以下是一个简单的C# FTP客户端示例,它展示了如何连接到FTP服务器并进行文件上传和下载操作。

C#
using System; using System.IO; using System.Net; public class SimpleFtpClient { private string _ftpServer; private string _userName; private string _password; public SimpleFtpClient(string ftpServer, string userName, string password) { _ftpServer = ftpServer; _userName = userName; _password = password; } /// <summary> /// 上传文件到FTP服务器 /// </summary> /// <param name="filePath">本地文件路径</param> /// <param name="ftpPath">服务器文件路径</param> public void UploadFile(string filePath, string ftpPath) { FileInfo fileInf = new FileInfo(filePath); string uri = "ftp://" + _ftpServer + "/" + ftpPath; // 创建FTP请求 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Ftp.UploadFile; // 登录凭证 request.Credentials = new NetworkCredential(_userName, _password); // 上传文件 using (FileStream fileStream = fileInf.OpenRead()) { using (Stream requestStream = request.GetRequestStream()) { byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } } } // 获取FTP服务器响应 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Console.WriteLine($"Upload File Complete, status {response.StatusDescription}"); } } /// <summary> /// 从FTP服务器下载文件 /// </summary> /// <param name="ftpPath">服务器文件路径</param> /// <param name="localPath">本地保存路径</param> public void DownloadFile(string ftpPath, string localPath) { string uri = "ftp://" + _ftpServer + "/" + ftpPath; // 创建FTP请求 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Ftp.DownloadFile; // 登录凭证 request.Credentials = new NetworkCredential(_userName, _password); // 下载文件 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (FileStream localFileStream = new FileStream(localPath, FileMode.Create)) { byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) != 0) { localFileStream.Write(buffer, 0, bytesRead); } } } Console.WriteLine($"Download Complete, status {response.StatusDescription}"); } } }

上传文件

C#
private void btnUpload_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "All files (*.*)|*.*"; openFileDialog1.Title = "Select a file to upload"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { string filename = openFileDialog1.FileName; FileInfo fileInfo = new FileInfo(filename); SimpleFtpClient ftpHelper = new SimpleFtpClient("127.0.0.1:21", "admin", "123456"); ftpHelper.UploadFile(filename, fileInfo.Name); MessageBox.Show("File uploaded successfully!"); } }

下载文件

C#
private void btnDownload_Click(object sender, EventArgs e) { SimpleFtpClient ftpHelper = new SimpleFtpClient("127.0.0.1:21", "admin", "123456"); SaveFileDialog saveFileDialog=new SaveFileDialog(); saveFileDialog.Filter = "All files (*.*)|*.*"; saveFileDialog.Title = "Select a file to download"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { string filename = saveFileDialog.FileName; ftpHelper.DownloadFile("1724843803807.png", filename); MessageBox.Show("File downloaded successfully!"); } }

列表服务器文件

C#
/// <summary> /// 列出FTP服务器上指定路径的文件和目录 /// </summary> /// <param name="path">服务器路径</param> public List<string> ListDirectory(string path) { string uri = "ftp://" + _ftpServer + "/" + path; List<string> lst = new List<string>(); // 创建FTP请求 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; // 登录凭证 request.Credentials = new NetworkCredential(_userName, _password); // 获取服务器响应 using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { // 使用特定编码读取流,这里使用UTF8编码 using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("GB2312"))) { string line; while ((line = reader.ReadLine()) != null) { lst.Add(line); } } } } return lst; }

image.png

注意事项

  • 确保FTP服务器地址、用户名和密码正确。
  • 检查FTP服务器的权限设置,确保具有上传和下载文件的权限。

通过以上示例,您可以实现一个基本的FTP客户端,并可根据需要进行扩展以支持更多功能和操作。

本文作者:rick

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!