在C#中,可以使用FtpWebRequest
类来进行FTP文件上传和下载。以下是一个简单的例子:
文件上传:
string ftpServerIP = "ftp://ftp.example.com/";
string ftpUsername = "username";
string ftpPassword = "password";
string filePath = "localfile.txt";
string ftpPath = "remotefile.txt";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerIP + ftpPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
using (FileStream fileStream = File.OpenRead(filePath))
using (Stream ftpStream = request.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
}
文件下载:
string ftpServerIP = "ftp://ftp.example.com/";
string ftpUsername = "username";
string ftpPassword = "password";
string ftpPath = "remotefile.txt";
string filePath = "localfile.txt";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerIP + ftpPath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream ftpStream = response.GetResponseStream())
using (FileStream fileStream = File.Create(filePath))
{
ftpStream.CopyTo(fileStream);
}
请注意,这些代码示例中的FTP服务器的URL、用户名和密码应更改为实际的值。