[C#][ASP.Net]FTP上的單檔下載

摘要:[C#][ASP.Net]FTP上的單檔下載
這裡列出三種下載方法:WebRequest,FtpWebRequest,以及WebClient。

這裡列出三種下載方法:WebRequestFtpWebRequest,以及WebClient

假設你有一個字串變數url記錄著要下載檔案的網路位址如下

string url = @"ftp://xxx.xxx.xxx.xxx/test.txt";

 

第一種方法 WebRequest

01 using System.Net;  //別忘記引用這個namespace
02 public string DownloadFile(string url, string username, string pw)
03 {
04     string strResult = "";
05     try
06     {
07         //最好使用Uri物件代替url字串,理由可以參考這邊.
08         //http://msdn.microsoft.com/zh-tw/library/ms182360.aspx
09         WebRequest oRequest = HttpWebRequest.Create(new Uri(url));
10         //設定登入帳號&密碼
11         oRequest.Credentials = new NetworkCredential(username, pw);
12         WebResponse oResponse = oRequest.GetResponse();
13
14         using (StreamReader sr = new StreamReader(oResponse.GetResponseStream()))

15         {
16             strResult = sr.ReadToEnd();
17             sr.Close();
18         }

19
20           oRequest = null;
21         oResponse = null;
22     }

23     catch (WebException wex)
24     {
25         //例外處理邏輯放這邊
26     }

27     return strResult;
28 }

 

第二種方法FtpWebRequest

01 private string DownloadFile(string url, string username, string pw)
02 {
03     string strResult = "";
04     try
05     {
06         //cast成FtpWebRequest類別
07         FtpWebRequest oFtpReq = (FtpWebRequest)WebRequest.Create(new Uri(url));
08         oFtpReq.Method = WebRequestMethods.Ftp.DownloadFile;
09
10         //set the username & password
11         oFtpReq.Credentials = new NetworkCredential(username, pw);
12
13         //因為只是簡單的text檔案,所以不需要用Binary模式
14         oFtpReq.UseBinary = false;
15
16         //如果你曾經得到類似下面的錯誤,則加入此行程式碼。
17         //The remote server returned an error: 227 Entering Passive Mode
18         oFtpReq.UsePassive = false;
19         FtpWebResponse oFtpResp = (FtpWebResponse)oFtpReq.GetResponse();
20
21         using (StreamReader sr = new StreamReader(oFtpResp.GetResponseStream()))
22         {
23             strResult = sr.ReadToEnd();
24             sr.Close();
25         }

26
27         oFtpResp.Close();
28         oFtpReq = null;
29         oFtpResp = null;
30     }

31     catch (WebException wex)
32     {
33         //
例外處理邏輯
34     }

35     return strResult;
36 }

此種方法支援斷點續傳,MS也是建議用此種方法從FTP下載檔案。

 

第三種WebClient

01 public string DownloadFile3(string url, string username, string pw)
07 {
08     string strResult = "";
09     try
10     {
11         using (WebClient oWebClient = new WebClient())
12         {
13             oWebClient.Credentials = new NetworkCredential(username, pw);
14             strResult = oWebClient.DownloadString(new Uri(url));
15         }

16     }

17     catch (WebException wex)
18     {
19         //
例外處理邏輯
20     }

21     return strResult;
22 }

 

附註:請記得此處只有用一個簡單的純文字檔做範例,如果你要下載的檔案不是純文字檔就要更改相關的設定。如果檔案比較大,最好用byte[]去承接stream。

參考: