iT邦幫忙

1

如何透過C#操作FTP連線

WM 2020-01-14 18:55:05318 瀏覽

首先利用pure-ftpd在Docker中,快速建立簡易型FTP。
不知如何安裝Docker,可以參考這篇
安裝指令:

docker run -d --name ftpd_server -p 21:21 -p 30000-30009:30000-30009 -e FTP_USER_HOME=/home/bob -e FTP_USER_NAME=bob -e FTP_USER_PASS=12345 -e "PUBLICHOST=localhost" stilliard/pure-ftpd

開啟檔案總管,在位址欄輸入ftp://localhost/後進入。
跳出對話視窗要求輸入安裝指令設定的帳號/密碼。

下載檔案:

建立一個txt,內容:成功接收自FTP回傳的資料流字元。
手動丟到FTP,此時FTP就會有檔案了:
https://ithelp.ithome.com.tw/upload/images/20200114/20112573gYrjpEeu3Y.png
Program.cs

var fileName = "test.txt";
// 建立跟FTP溝通的物件
FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"ftp://localhost/{fileName}");
request.Method = WebRequestMethods.Ftp.DownloadFile;
 // 輸入帳號/密碼登入FTP.
 request.Credentials = new NetworkCredential("bob", "12345");
//建立物件接收FTP的回應
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//建立物件接收從FTP回應的資料流
Stream responseStream = response.GetResponseStream();
//建立物件讀取資料流的字元
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
reader.Close();
response.Close();

執行結果:
https://ithelp.ithome.com.tw/upload/images/20200114/20112573ay0zodrtwp.png

上傳檔案:

Program.cs

//欲建立在FTP的檔案名稱
var fileName = "test.txt";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"ftp://localhost/{fileName}");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("bob", "12345");
byte[] fileContents;
//建立StreamReader物件讀取實體檔案,並轉成byte陣列
using (StreamReader sourceStream = new StreamReader(@"C:\test.txt"))
{
    fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
//將byte陣列寫入Stream資料流
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(fileContents, 0, fileContents.Length);
}
//建立FtpWebResponse物件接收從FTP回應的資料流
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
    Console.WriteLine($"Upload File Complete, status {response.StatusDescription}");
}

執行結果:
https://ithelp.ithome.com.tw/upload/images/20200114/20112573nph7esXgqY.png
此時的FTP會多一個test1.txt:
https://ithelp.ithome.com.tw/upload/images/20200114/20112573jOOzkuGste.png

參考資料:
How to: Download files with FTP | Microsoft Docs
How to: Upload files with FTP | Microsoft Docs


尚未有邦友留言

立即登入留言