欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现文件断点续传下载的方法

程序员文章站 2022-04-11 08:20:55
本文实例讲述了c#实现文件断点续传下载的方法。分享给大家供大家参考。具体实现方法如下: using system; using system.data; us...

本文实例讲述了c#实现文件断点续传下载的方法。分享给大家供大家参考。具体实现方法如下:

using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.io;
using system.text;
using system.net;
namespace simpledemo
{
 class program
 {
  /// <summary>
  /// 下载文件保留字
  /// </summary>
  public static string persist_exp = ".cdel";
  /// <summary> 
  public static void main(string[] args)
  {
   string path = "d:\\aa.txt";
   string ec = getfileencoding(path, "gb2312");
   print("coding: " + ec);
   // string content = filereader(path, encoding.getencoding(ec));
   // print(content);
   //filewriter(path, "测试内容11", encoding.getencoding(ec));
   string url = "http://www.xxx.com/20120920172200024.flv";
   string path1 = "d:\\aa1.flv";

   download(url, path1);
   //gapdownload(url, path1);
   //t(url);
  }
  public static void t(string url) {
   httpwebrequest request = (system.net.httpwebrequest)httpwebrequest.create(url);

   //webresponse response = httpclient.creategethttpresponse(url, 3000, null, null);
   try {
    webresponse response = request.getresponse();
    webheadercollection headers = response.headers;
    print(response.contentlength);
    request = (system.net.httpwebrequest)httpwebrequest.create(url);
    request.addrange(11); //设置range值
    webresponse response1 = request.getresponse();
    print(response1.contentlength);

    foreach (string key in headers)
    {
     print(key + "----- " + headers.get(key));
    }
    string disposition = headers.get("content-disposition");
    print(disposition);
   }catch(exception e){
    print(e.message);
   }
   //string filename = disposition.substring(disposition.indexof("\""));
   //print(filename);
  }
  public static void download(string url, string path) {
   if (file.exists(path))
   {
    print("文件己存在!是否重新下载?");
    return;
   }
   else {
    path = path + persist_exp;
    simpledownload(url,path);//开始下载
   } 
  }
  /// <summary>
  /// 下载网络资源(支持断点续传)
  /// </summary>
  /// <param name="url"></param>
  /// <param name="path"></param>
  public static void simpledownload(string url, string path)
  {
   httpwebrequest request = httpclient.getwebrequest(url, 0);
   webresponse response = null;
   filestream writer = new filestream(path, filemode.openorcreate, fileaccess.write);
   long lstartpos = writer.length; ;//当前文件大小
   long currentlength = 0;
   long totallength = 0;//总大小 
   if (file.exists(path))//断点续传
   {
    response = request.getresponse();
    long stotal = response.contentlength;
    if (stotal == lstartpos) {
     close(writer);
     file.move(path, path.replace(persist_exp, ""));
     print("下载完成!");
     return;
    }
    request = httpclient.getwebrequest(url, (int)lstartpos);
    //设置range值
    writer.seek(lstartpos, seekorigin.begin);//指针跳转
    response = request.getresponse();
    totallength = response.contentlength + lstartpos; //总长度
    currentlength = lstartpos; //当前长度
   }
   else
   {
    response = request.getresponse();
    totallength = response.contentlength;
   }
   stream reader = response.getresponsestream();
   byte[] buff = new byte[1024];
   int c = 0; //实际读取的字节数
   while ((c = reader.read(buff, 0, buff.length)) > 0)
   {
    currentlength += c;
    writer.write(buff, 0, c);
    progressbar(currentlength, totallength);//进度条
    writer.flush();
   }
   close(writer);
   if (currentlength == totallength)
   {
    file.move(path, path.replace(persist_exp, ""));
    print("下载完成!");
   }

   if (reader != null)
   {
    reader.close();
    reader.dispose();
    response.close();
   }
  }
  private static void close(filestream writer)
  {
   if (writer != null)
   {
    writer.close();
    writer.dispose();
   }
  }
  /// <summary>
  /// 进度条
  /// </summary>
  /// <param name="currentlength">当前长度</param>
  /// <param name="totallength">总长度</param>
  public static void progressbar(object currentlength, object totallength)
  {
   double aaa = system.convert.todouble(currentlength);
   double bbb = system.convert.todouble(totallength);
   print(currentlength + "/" + totallength + "__" + (aaa / bbb).tostring("0.00 %"));
  }
  /// <summary>
  /// 系统输出
  /// </summary>
  /// <param name="obj"></param>
  public static void print(object obj){
   console.writeline(obj);
  }
  public static void printstr(string[] str)
  {
   foreach (string d in str)
   {
    print(d);
   }
  }
  /// <summary>
  /// 文件写
  /// </summary>
  /// <param name="path">文件路径</param>
  /// <param name="content">要写入的内容</param>
  public static void filewriter(string path,string content,encoding encoding)
  {
   if (file.exists(path))
   {
    streamwriter sw = new streamwriter(path, true, encoding);
    sw.writeline(content);
    sw.flush();
    sw.close();
   }
  }
  /// <summary>
  /// 读文件,返回内容
  /// </summary>
  /// <param name="path">文件路径</param>
  /// <param name="encoding">默认编码格式</param>
  /// <returns></returns>
  public static string filereader(string path,encoding encoding) {
   stringbuilder sb = new stringbuilder();
   if(encoding == null){
    encoding = encoding.default;
   }
   //读取文件
   streamreader sr = new streamreader(path, encoding);
    string s = "";
    while ((s = sr.readline()) != null)
    {
     sb.appendline(s);
    }
    if(sr != null)
     sr.close();
   return sb.tostring();
  }
  /// <summary>
  /// 获取文件编码格式
  /// </summary>
  /// <param name="path">文件路径</param>
  /// <param name="defaultencoding">默认编码</param>
  /// <returns></returns>
  public static string getfileencoding(string path, string defaultencoding) {
   string ed = defaultencoding;
   if (file.exists(path)) {
    filestream fs = new filestream(path, filemode.open);
    ed = getencoding(fs, defaultencoding);
    if (fs != null)
     fs.close(); 
   }
   return ed;
  }
  /// <summary>
  /// 取得一个文本文件流的编码方式。
  /// </summary>
  /// <param name="stream">文本文件流。</param>
  /// <param name="defaultencoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
  /// <returns></returns>
  public static string getencoding(filestream stream, string defaultencoding)
  {
   string targetencoding = defaultencoding;
   if (stream != null && stream.length >= 2)
   {
    //保存文件流的前4个字节
    byte byte1 = 0;
    byte byte2 = 0;
    byte byte3 = 0;
    byte byte4 = 0;
    //保存当前seek位置
    long origpos = stream.seek(0, seekorigin.begin);
    stream.seek(0, seekorigin.begin);
    int nbyte = stream.readbyte();
    byte1 = convert.tobyte(nbyte);
    byte2 = convert.tobyte(stream.readbyte());
    if (stream.length >= 3)
    {
     byte3 = convert.tobyte(stream.readbyte());
    }
    if (stream.length >= 4)
    {
     byte4 = convert.tobyte(stream.readbyte());
    }
    //根据文件流的前4个字节判断encoding
    //unicode {0xff, 0xfe};
    //be-unicode {0xfe, 0xff};
    //utf8 = {0xef, 0xbb, 0xbf};
    if (byte1 == 0xfe && byte2 == 0xff)//unicodebe
    {
     targetencoding = encoding.bigendianunicode.bodyname;
    }
    if (byte1 == 0xff && byte2 == 0xfe && byte3 != 0xff)//unicode
    {
     targetencoding = encoding.unicode.bodyname;
    }
    if (byte1 == 0xef && byte2 == 0xbb && byte3 == 0xbf)//utf8
    {
     targetencoding = encoding.utf8.bodyname;
    }
    //恢复seek位置 
    stream.seek(origpos, seekorigin.begin);
   }
   return targetencoding;
  }
 }
}

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.net;
using system.net.security;
using system.security.cryptography.x509certificates;
using system.io;
namespace simpledemo
{
 /// <summary>
 /// 公用 http 请求类
 /// </summary>
 class httpclient
 {
  /// <summary>
  /// 获取基础webrequest
  /// </summary>
  /// <param name="url">请求地址</param>
  /// <param name="lstartpos">请求的开始位置</param>
  /// <returns></returns>
  public static httpwebrequest getwebrequest(string url, int lstartpos)
  {
   httpwebrequest request = null;
   try
   {
    request = (system.net.httpwebrequest)httpwebrequest.create(url);
    request.addrange(lstartpos); //设置range值
   }
   catch (exception ex)
   {
    program.print(ex.message);
   }
   return request;
  }
 }
}

希望本文所述对大家的c#程序设计有所帮助。