[C#] C#实现文件下载,支持断点续传 →→→→→进入此内容的聊天室

来自 , 2020-03-09, 写在 C#, 查看 172 次.
URL http://www.code666.cn/view/6f5216f8
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.IO;
  7. using System.Text;
  8. using System.Net;
  9. namespace simpleDemo
  10. {
  11.    
  12.     class Program
  13.     {
  14.         /// <summary>
  15.         /// 下载文件保留字
  16.         /// </summary>
  17.         public static string PERSIST_EXP = ".cdel";
  18.         /// <summary>  
  19.         public static void Main(string[] args)
  20.         {
  21.  
  22.             string path = "D:\\aa.txt";
  23.  
  24.             string ec = getFileEncoding(path, "GB2312");
  25.             print("coding: " + ec);
  26.  
  27.             // string content = fileReader(path, Encoding.GetEncoding(ec));
  28.             // print(content);
  29.  
  30.             //fileWriter(path, "测试内容11", Encoding.GetEncoding(ec));
  31.  
  32.             string url = "http://www.XXX.com/20120920172200024.flv";
  33.             string path1 = "D:\\aa1.flv";
  34.  
  35.  
  36.             download(url, path1);
  37.             //gapDownload(url, path1);
  38.             //t(url);
  39.            
  40.         }
  41.         public static void t(string url) {
  42.            
  43.             HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);
  44.  
  45.  
  46.             //WebResponse response = httpClient.CreateGetHttpResponse(url, 3000, null, null);
  47.  
  48.             try {
  49.                
  50.                 WebResponse response = request.GetResponse();
  51.  
  52.                 WebHeaderCollection headers = response.Headers;
  53.  
  54.                 print(response.ContentLength);
  55.  
  56.                 request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);
  57.                 request.AddRange(11); //设置Range值
  58.                 WebResponse response1 = request.GetResponse();
  59.                 print(response1.ContentLength);
  60.  
  61.  
  62.                 foreach (string key in headers)
  63.                 {
  64.                     print(key + "----- " + headers.Get(key));
  65.                 }
  66.  
  67.                 string disposition = headers.Get("Content-Disposition");
  68.  
  69.                 print(disposition);
  70.             }catch(Exception e){
  71.                 print(e.Message);
  72.             }
  73.  
  74.             //string fileName = disposition.Substring(disposition.IndexOf("\""));
  75.  
  76.             //print(fileName);
  77.          
  78.         }
  79.         public static void download(string url, string path) {
  80.             if (File.Exists(path))
  81.             {
  82.                 print("文件己存在!是否重新下载?");
  83.                 return;
  84.             }
  85.             else {
  86.                 path = path + PERSIST_EXP;
  87.  
  88.                 simpleDownload(url,path);//开始下载
  89.             }  
  90.         }
  91.         /// <summary>
  92.         /// 下载网络资源(支持断点续传)
  93.         /// </summary>
  94.         /// <param name="url"></param>
  95.         /// <param name="path"></param>
  96.         public static void simpleDownload(string url, string path)
  97.         {
  98.             HttpWebRequest request = httpClient.getWebRequest(url, 0);
  99.            
  100.             WebResponse response = null;
  101.  
  102.             FileStream writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
  103.             long lStartPos = writer.Length; ;//当前文件大小
  104.             long currentLength = 0;
  105.             long totalLength = 0;//总大小
  106.            
  107.             if (File.Exists(path))//断点续传
  108.             {
  109.                 response = request.GetResponse();
  110.                 long sTotal = response.ContentLength;
  111.  
  112.                 if (sTotal == lStartPos) {
  113.  
  114.                     close(writer);
  115.                     File.Move(path, path.Replace(PERSIST_EXP, ""));
  116.                     print("下载完成!");
  117.                     return;
  118.  
  119.                 }
  120.                 request = httpClient.getWebRequest(url, (int)lStartPos);//设置Range值
  121.  
  122.                 writer.Seek(lStartPos, SeekOrigin.Begin);//指针跳转
  123.                 response = request.GetResponse();
  124.  
  125.                 totalLength = response.ContentLength + lStartPos; //总长度
  126.                 currentLength = lStartPos; //当前长度
  127.             }
  128.             else
  129.             {
  130.                 response = request.GetResponse();
  131.                 totalLength = response.ContentLength;
  132.             }
  133.  
  134.             Stream reader = response.GetResponseStream();
  135.  
  136.             byte[] buff = new byte[1024];
  137.             int c = 0; //实际读取的字节数
  138.  
  139.             while ((c = reader.Read(buff, 0, buff.Length)) > 0)
  140.             {
  141.                 currentLength += c;
  142.                 writer.Write(buff, 0, c);
  143.                 progressBar(currentLength, totalLength);//进度条
  144.  
  145.                 writer.Flush();
  146.             }
  147.             close(writer);
  148.             if (currentLength == totalLength)
  149.             {
  150.                 File.Move(path, path.Replace(PERSIST_EXP, ""));
  151.                 print("下载完成!");
  152.             }
  153.          
  154.  
  155.             if (reader != null)
  156.             {
  157.                 reader.Close();
  158.                 reader.Dispose();
  159.                 response.Close();
  160.             }
  161.         }
  162.         private static void close(FileStream writer)
  163.         {
  164.             if (writer != null)
  165.             {
  166.                 writer.Close();
  167.                 writer.Dispose();
  168.             }
  169.         }
  170.         /// <summary>
  171.         /// 进度条
  172.         /// </summary>
  173.         /// <param name="currentLength">当前长度</param>
  174.         /// <param name="totalLength">总长度</param>
  175.         public static void progressBar(Object currentLength, Object totalLength)
  176.         {
  177.             double aaa = System.Convert.ToDouble(currentLength);
  178.             double bbb = System.Convert.ToDouble(totalLength);
  179.             print(currentLength + "/" + totalLength + "__" + (aaa / bbb).ToString("0.00 %"));
  180.         }
  181.         /// <summary>
  182.         /// 系统输出
  183.         /// </summary>
  184.         /// <param name="obj"></param>
  185.         public static void print(Object obj){
  186.             Console.WriteLine(obj);
  187.         }
  188.         public static void printStr(string[] str)
  189.         {
  190.             foreach (string d in str)
  191.             {
  192.                 print(d);
  193.             }
  194.         }
  195.         /// <summary>
  196.         /// 文件写
  197.         /// </summary>
  198.         /// <param name="path">文件路径</param>
  199.         /// <param name="content">要写入的内容</param>
  200.         public static void fileWriter(string path,string content,Encoding encoding)
  201.         {
  202.             if (File.Exists(path))
  203.             {
  204.                 StreamWriter sw = new StreamWriter(path, true, encoding);
  205.                
  206.                 sw.WriteLine(content);
  207.  
  208.                 sw.Flush();
  209.                 sw.Close();
  210.             }
  211.         }
  212.         /// <summary>
  213.         /// 读文件,返回内容
  214.         /// </summary>
  215.         /// <param name="path">文件路径</param>
  216.         /// <param name="enCoding">默认编码格式</param>
  217.         /// <returns></returns>
  218.         public static string fileReader(string path,Encoding enCoding) {
  219.             StringBuilder sb = new StringBuilder();
  220.             if(enCoding == null){
  221.                 enCoding = Encoding.Default;
  222.             }
  223.             //读取文件
  224.             StreamReader sr = new StreamReader(path, enCoding);
  225.                 string s = "";
  226.                 while ((s = sr.ReadLine()) != null)
  227.                 {
  228.                     sb.AppendLine(s);
  229.                 }
  230.                 if(sr != null)
  231.                     sr.Close();
  232.  
  233.             return sb.ToString();
  234.         }
  235.         /// <summary>
  236.         /// 获取文件编码格式
  237.         /// </summary>
  238.         /// <param name="path">文件路径</param>
  239.         /// <param name="defaultEncoding">默认编码</param>
  240.         /// <returns></returns>
  241.         public static string getFileEncoding(string path, string defaultEncoding) {
  242.             string ed = defaultEncoding;
  243.             if (File.Exists(path)) {
  244.                 FileStream fs = new FileStream(path, FileMode.Open);
  245.                 ed = GetEncoding(fs, defaultEncoding);
  246.                 if (fs != null)
  247.                     fs.Close();  
  248.             }
  249.             return ed;
  250.         }
  251.         /// <summary>
  252.         /// 取得一个文本文件流的编码方式。
  253.         /// </summary>
  254.         /// <param name="stream">文本文件流。</param>
  255.         /// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
  256.         /// <returns></returns>
  257.         public static string GetEncoding(FileStream stream, string defaultEncoding)
  258.         {
  259.             string targetEncoding = defaultEncoding;
  260.             if (stream != null && stream.Length >= 2)
  261.             {
  262.                 //保存文件流的前4个字节
  263.                 byte byte1 = 0;
  264.                 byte byte2 = 0;
  265.                 byte byte3 = 0;
  266.                 byte byte4 = 0;
  267.                 //保存当前Seek位置
  268.                 long origPos = stream.Seek(0, SeekOrigin.Begin);
  269.                 stream.Seek(0, SeekOrigin.Begin);
  270.  
  271.                 int nByte = stream.ReadByte();
  272.                 byte1 = Convert.ToByte(nByte);
  273.                 byte2 = Convert.ToByte(stream.ReadByte());
  274.                 if (stream.Length >= 3)
  275.                 {
  276.                     byte3 = Convert.ToByte(stream.ReadByte());
  277.                 }
  278.                 if (stream.Length >= 4)
  279.                 {
  280.                     byte4 = Convert.ToByte(stream.ReadByte());
  281.                 }
  282.                 //根据文件流的前4个字节判断Encoding
  283.                 //Unicode {0xFF, 0xFE};
  284.                 //BE-Unicode {0xFE, 0xFF};
  285.                 //UTF8 = {0xEF, 0xBB, 0xBF};
  286.                 if (byte1 == 0xFE && byte2 == 0xFF)//UnicodeBe
  287.                 {
  288.                     targetEncoding = Encoding.BigEndianUnicode.BodyName;
  289.                 }
  290.                 if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode
  291.                 {
  292.                     targetEncoding = Encoding.Unicode.BodyName;
  293.                 }
  294.                 if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8
  295.                 {
  296.                     targetEncoding = Encoding.UTF8.BodyName;
  297.                 }
  298.                 //恢复Seek位置
  299.                 stream.Seek(origPos, SeekOrigin.Begin);
  300.             }
  301.             return targetEncoding;
  302.         }
  303.  
  304.     }
  305. }
  306.  
  307.  
  308.  
  309.  
  310.  
  311. using System;
  312. using System.Collections.Generic;
  313. using System.Linq;
  314. using System.Text;
  315. using System.Net;
  316. using System.Net.Security;
  317. using System.Security.Cryptography.X509Certificates;
  318. using System.IO;
  319.  
  320. namespace simpleDemo
  321. {
  322.     /// <summary>
  323.     /// 公用 Http 请求类
  324.     /// </summary>
  325.     class httpClient
  326.     {
  327.         /// <summary>
  328.         /// 获取基础WebRequest
  329.         /// </summary>
  330.         /// <param name="url">请求地址</param>
  331.         /// <param name="lStartPos">请求的开始位置</param>
  332.         /// <returns></returns>
  333.         public static HttpWebRequest getWebRequest(string url, int lStartPos)
  334.         {
  335.             HttpWebRequest request = null;
  336.             try
  337.             {
  338.                 request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);
  339.                 request.AddRange(lStartPos); //设置Range值
  340.             }
  341.             catch (Exception ex)
  342.             {
  343.                 Program.print(ex.Message);
  344.             }
  345.  
  346.             return request;
  347.         }
  348.     }
  349. }
  350. //csharp/5646

回复 "C#实现文件下载,支持断点续传"

这儿你可以回复上面这条便签

captcha