在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、用戶名和密碼應更改為實際的值。