從ftp伺服器下載檔案步驟如下:
1. 建立ftp物件, 連結FTP伺服器
建立FtpWebRequest的物件 request, 並與ftp伺服器的檔案連結.
using System.Net;
FtpWebRequest request = FtpWebRequest.Create(FTPString) as FtpWebRequest;
// FTPString = FTPAddress + "/" + filename
2. 用userid和password登入ftp伺服器
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
3. 將keepalive屬性設為True, 重複使用同一物件實體(instance)
request.KeepAlive = true; ///執行後不要關閉連結
request.UsePassive = true;
4. 使用binary方法傳送資料
request.UseBinary = true;
5. 將ftp檔案讀入buffer
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
Stream reader = response.GetResponseStream();
MemoryStream memStream = new MemoryStream();
byte[] buffer = new byte[1024]; //每次讀取1024 bytes
while (true)
{
Application.DoEvents();
int bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
//已經沒有資料, 結束下載
Application.DoEvents();
break;
}
else
{
//資料寫入buffer
memStream.Write(buffer, 0, bytesRead);
}
}
byte[] downloadedData = memStream.ToArray();
reader.Close();
memStream.Close();
response.Close();
6. 存檔
用filestream開啟本地磁碟機檔案, 並將檔案資料由 FileStream
FileStream newFile = new FileStream(saveFile1.FileName, FileMode.Create);
newFile.Write(downloadedData, 0, downloadedData.Length);
newFile.Close();
FtpWebReguest物件的其他方法
建立目錄
FtpWebRequest Request = (FtpWebRequest)WebRequest.Create("ftp://IP address/Directory");
Request.Credentials = new NetworkCredential("id", "pwd");
Request.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse Response = (FtpWebResponse)Request.GetResponse();
Response.Close();
修改檔案名稱
FtpWebRequest Request = (FtpWebRequest)WebRequest.Create("ftp://IP address/FileName");
Request.Credentials = new NetworkCredential("id", "pwd");
Request.Method = WebRequestMethods.Ftp.Rename;
Request.RenameTo = "NewFileName";
FtpWebResponse Response = (FtpWebResponse)Request.GetResponse();
Response.Close();
移除檔案
FtpWebRequest Request = (FtpWebRequest)WebRequest.Create ("ftp://IP address/FileName");
Request.Credentials = new NetworkCredential("id", "pwd");
Request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse Response = (FtpWebResponse)Request.GetResponse();
Response.Close();
參考資料來源:
C# FTP Upload
C# Download File FTP
文章定位: