试验FtpWebRequest的断点续传

来源:互联网 发布:php header导出excel 编辑:程序博客网 时间:2024/05/21 10:46
//下载文件的URI
 Uri u = new Uri("ftp://localhost/test.txt");
 //设定下载文件的保存路径
 string downFile = "C:\\test.txt";
 
 //FtpWebRequest的作成
 System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
     System.Net.WebRequest.Create(u);
 //设定用户名和密码
 ftpReq.Credentials = new System.Net.NetworkCredential("username""password");
 //MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定
 ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
 //要求终了后关闭连接
 ftpReq.KeepAlive = false;
 //使用ASCII方式传送
 ftpReq.UseBinary = false;
 //设定PASSIVE方式无效
 ftpReq.UsePassive = false;
  
 //判断是否继续下载
 //继续写入下载文件的FileStream
 System.IO.FileStream fs;
 if (System.IO.File.Exists(downFile))
 {
     //继续下载
     ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;
     fs = new System.IO.FileStream(
         downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);
 }
 else
 {
     //一般下载
     fs = new System.IO.FileStream(
         downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
 }
 
 //取得FtpWebResponse
 System.Net.FtpWebResponse ftpRes =
     (System.Net.FtpWebResponse)ftpReq.GetResponse();
 //为了下载文件取得Stream
 System.IO.Stream resStrm = ftpRes.GetResponseStream();
 //写入下载的数据
 byte[] buffer = new byte[1024];
 while (true)
 {
     int readSize = resStrm.Read(buffer, 0, buffer.Length);
     if (readSize == 0)
         break;
     fs.Write(buffer, 0, readSize);
 }
 fs.Close();
 resStrm.Close();
  
 //表示从FTP服务器被送信的状态
 Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
 //关闭连接
 ftpRes.Close();