1: private void test()
2: { 3: //宣告FTP連線
4: FtpWebRequest ftpReq = (FtpWebRequest)
5: WebRequest.Create("ftp://ftp.darkthread.net/download/some.zip"); 6: //下載檔案
7: ftpReq.Method = WebRequestMethods.Ftp.DownloadFile;
8: //指定Username/Password
9: ftpReq.Credentials = new NetworkCredential("username", "password"); 10: //指定BIN模式
11: ftpReq.UseBinary = true;
12: string zipFile = "c:\\temp\some.zip";
13: //支援續傳功能
14: FileInfo fi = new FileInfo(zipFile);
15: FileStream fs = null;
16: //檢測檔案是否存在
17: if (fi.Exists)
18: { 19: //檔案若存在,由剛才的中斷點繼續
20: ftpReq.ContentOffset = fi.Length;
21: fs = new FileStream(zipFile, FileMode.Append, FileAccess.Write);
22: }
23: else //檔案不存在時重新建立新檔案
24: fs = new FileStream(zipFile, FileMode.Create, FileAccess.Write);
25: //建立FTP連線
26: FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
27: //取得下載用的Stream物件
28: using (Stream stm = ftpResp.GetResponseStream())
29: { 30: //由於檔案龐大,以Block方式多批寫入
31: byte[] buff = new byte[2048];
32: int len = 0;
33: while (fs.Length < ftpResp.ContentLength)
34: { 35: //取得資料長度
36: len = stm.Read(buff, 0, buff.Length);
37: fs.Write(buff, 0, len);
38: }
39: stm.Close();
40:
41: }
42: fs.Flush();
43: fs.Close();
44: }