试验FtpWebRequest的断点续传

//下载文件的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();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值