FTP(File Transfer Protocol,文件传输协议)是一种用于在客户端和服务器之间传输文件的标准网络协议。使用C#编程语言,我们可以轻松实现一个FTP客户端。本文将探讨如何实现基本的FTP功能,包括连接FTP服务器、上传和下载文件。
FtpWebRequest
类,使得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;
}
通过以上示例,您可以实现一个基本的FTP客户端,并可根据需要进行扩展以支持更多功能和操作。
本文作者:rick
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!