.NET Framework 2.0 原生支援 FTP 協定,透過 FtpWebRequest / FtpWebResponse 即可實作上傳、下載、列表、刪除、重命名等操作,無需第三方套件。本文提供完整可用的 C# 範例代碼。
FtpWebRequest 指向 FTP 伺服器 URIMethod 屬性(WebRequestMethods.Ftp.UploadFile、DownloadFile、ListDirectory 等)Credentials(帳密)、UseBinary(二進位/ASCII)、UsePassive(被動模式)、KeepAlive、EnableSsltrue,否則帳密明文傳輸極不安全。private void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
const int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
using (FileStream fs = fileInf.OpenRead())
using (Stream strm = reqFTP.GetRequestStream())
{
while ((contentLen = fs.Read(buff, 0, buffLength)) != 0)
{
strm.Write(buff, 0, contentLen);
}
}
}
private void Download(string filePath, string fileName)
{
string fullPath = Path.Combine(filePath, fileName);
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
using (Stream ftpStream = response.GetResponseStream())
using (FileStream outputStream = new FileStream(fullPath, FileMode.Create))
{
byte[] buffer = new byte[2048];
int readCount;
while ((readCount = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, readCount);
}
}
}
public string[] GetFileList()
{
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
using (WebResponse response = reqFTP.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string result = reader.ReadToEnd().TrimEnd('\n');
return result.Split('\n');
}
}
Method = WebRequestMethods.Ftp.DeleteFileRenameTo 屬性,Method = WebRequestMethods.Ftp.RenameMethod = WebRequestMethods.Ftp.MakeDirectoryMethod = WebRequestMethods.Ftp.GetFileSize,回應的 ContentLength 即為大小EnableSsl = true,否則帳密明文傳輸。WebException 檢查 Response 的 StatusCode 與 StatusDescription 進行錯誤診斷。SecurityException。