DownLodThreading.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading;
  8. namespace Falit.Run.Utils
  9. {
  10. //var mt = new DownLodThreading(10, AppConfig._WebApiURL + verFileList[i].Path,
  11. // AppDomain.CurrentDomain.BaseDirectory + $"/{result.Data.Ver}/");
  12. //mt._fileName = verFileList[i].Name;
  13. // mt.Start();
  14. // _SumDownLoadSize = _SumDownLoadSize + (int) mt._fileSize;
  15. //pbrLoading.Maximum = _SumDownLoadSize;
  16. // Thread bar = new Thread(() =>
  17. // {
  18. // dataViewFile.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
  19. // while (!mt._isComplete)
  20. // {
  21. // Thread.Sleep(50);
  22. // pbrLoading.Value = mt._downloadSize;
  23. // _CurrentDownLoadSize = mt._downloadSize;
  24. // dataViewFile.Rows[i].Cells["进度"].Value =
  25. // string.Format("0:F", (float)(i + 1) / mt._downloadSize * 100 + "%");
  26. // }
  27. // dataViewFile.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
  28. // dataViewFile.Rows[i].Cells["进度"].Value = "100%";
  29. // });
  30. //dataViewFile.CurrentCell = dataViewFile.Rows[i].Cells[0];
  31. // bar.Start();
  32. /// <summary>
  33. /// 多线程下载单一文件
  34. /// </summary>
  35. public class DownLodThreading
  36. {
  37. public int _threadNum; //线程数量
  38. public long _fileSize; //文件大小
  39. public string _extName; //文件扩展名
  40. public string _fileUrl; //文件地址
  41. public string _fileName; //文件名
  42. public string _savePath; //保存路径
  43. public short _threadCompleteNum; //线程完成数量
  44. public bool _isComplete; //是否完成
  45. public volatile int _downloadSize; //当前下载大小
  46. public Thread[] _thread; //线程数组
  47. public List<string> _tempFiles = new List<string>();
  48. public DownLodThreading(int threahNum, string fileUrl, string savePath)
  49. {
  50. this._threadNum = threahNum;
  51. this._thread = new Thread[threahNum];
  52. this._fileUrl = fileUrl;
  53. this._savePath = savePath;
  54. }
  55. public void Start()
  56. {
  57. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fileUrl);
  58. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  59. _extName = response.ResponseUri.ToString().Substring(response.ResponseUri.ToString().LastIndexOf('.'));//获取真实扩展名
  60. _fileSize = response.ContentLength;
  61. int singelNum = (int)(_fileSize / _threadNum); //平均分配
  62. int remainder = (int)(_fileSize % _threadNum); //获取剩余的
  63. request.Abort();
  64. response.Close();
  65. for (int i = 0; i < _threadNum; i++)
  66. {
  67. List<int> range = new List<int>();
  68. range.Add(i * singelNum);
  69. if (remainder != 0 && (_threadNum - 1) == i) //剩余的交给最后一个线程
  70. range.Add(i * singelNum + singelNum + remainder - 1);
  71. else
  72. range.Add(i * singelNum + singelNum - 1);
  73. _thread[i] = new Thread(() => { Download(range[0], range[1]); });
  74. _thread[i].Name = string.Format("Thread {0}", i + 1);
  75. _thread[i].Start();
  76. }
  77. }
  78. private void Download(int from, int to)
  79. {
  80. Stream httpFileStream = null, localFileStram = null;
  81. try
  82. {
  83. string tmpFileBlock = string.Format(@"{0}\{1}_{2}.dat", _savePath, _fileName, Thread.CurrentThread.Name);
  84. _tempFiles.Add(tmpFileBlock);
  85. HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(_fileUrl);
  86. httprequest.AddRange(from, to);
  87. HttpWebResponse httpresponse = (HttpWebResponse)httprequest.GetResponse();
  88. httpFileStream = httpresponse.GetResponseStream();
  89. localFileStram = new FileStream(tmpFileBlock, FileMode.Create);
  90. byte[] by = new byte[5000];
  91. int getByteSize = httpFileStream.Read(by, 0, (int)by.Length); //Read方法将返回读入by变量中的总字节数
  92. while (getByteSize > 0)
  93. {
  94. Thread.Sleep(20);
  95. _downloadSize += getByteSize;
  96. localFileStram.Write(by, 0, getByteSize);
  97. getByteSize = httpFileStream.Read(by, 0, (int)by.Length);
  98. }
  99. _threadCompleteNum++;
  100. }
  101. catch (Exception ex)
  102. {
  103. throw new Exception(ex.Message.ToString());
  104. }
  105. finally
  106. {
  107. if (httpFileStream != null) httpFileStream.Dispose();
  108. if (localFileStram != null) localFileStram.Dispose();
  109. }
  110. if (_threadCompleteNum == _threadNum)
  111. {
  112. _isComplete = true;
  113. Complete();
  114. }
  115. }
  116. private void Complete()
  117. {
  118. Stream mergeFile = new FileStream(
  119. string.Format(@"{0}\{1}{2}", _savePath, _fileName, _extName), FileMode.Create);
  120. BinaryWriter AddWriter = new BinaryWriter(mergeFile);
  121. foreach (string file in _tempFiles)
  122. {
  123. using (FileStream fs = new FileStream(file, FileMode.Open))
  124. {
  125. BinaryReader TempReader = new BinaryReader(fs);
  126. AddWriter.Write(TempReader.ReadBytes((int)fs.Length));
  127. TempReader.Close();
  128. }
  129. File.Delete(file);
  130. }
  131. AddWriter.Close();
  132. }
  133. }
  134. }