123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading;
- namespace Falit.Run.Utils
- {
- //var mt = new DownLodThreading(10, AppConfig._WebApiURL + verFileList[i].Path,
- // AppDomain.CurrentDomain.BaseDirectory + $"/{result.Data.Ver}/");
- //mt._fileName = verFileList[i].Name;
- // mt.Start();
- // _SumDownLoadSize = _SumDownLoadSize + (int) mt._fileSize;
- //pbrLoading.Maximum = _SumDownLoadSize;
- // Thread bar = new Thread(() =>
- // {
- // dataViewFile.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
- // while (!mt._isComplete)
- // {
- // Thread.Sleep(50);
- // pbrLoading.Value = mt._downloadSize;
- // _CurrentDownLoadSize = mt._downloadSize;
- // dataViewFile.Rows[i].Cells["进度"].Value =
- // string.Format("0:F", (float)(i + 1) / mt._downloadSize * 100 + "%");
- // }
- // dataViewFile.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
- // dataViewFile.Rows[i].Cells["进度"].Value = "100%";
- // });
- //dataViewFile.CurrentCell = dataViewFile.Rows[i].Cells[0];
- // bar.Start();
- /// <summary>
- /// 多线程下载单一文件
- /// </summary>
- public class DownLodThreading
- {
- public int _threadNum; //线程数量
- public long _fileSize; //文件大小
- public string _extName; //文件扩展名
- public string _fileUrl; //文件地址
- public string _fileName; //文件名
- public string _savePath; //保存路径
- public short _threadCompleteNum; //线程完成数量
- public bool _isComplete; //是否完成
- public volatile int _downloadSize; //当前下载大小
- public Thread[] _thread; //线程数组
- public List<string> _tempFiles = new List<string>();
- public DownLodThreading(int threahNum, string fileUrl, string savePath)
- {
- this._threadNum = threahNum;
- this._thread = new Thread[threahNum];
- this._fileUrl = fileUrl;
- this._savePath = savePath;
- }
- public void Start()
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fileUrl);
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- _extName = response.ResponseUri.ToString().Substring(response.ResponseUri.ToString().LastIndexOf('.'));//获取真实扩展名
- _fileSize = response.ContentLength;
- int singelNum = (int)(_fileSize / _threadNum); //平均分配
- int remainder = (int)(_fileSize % _threadNum); //获取剩余的
- request.Abort();
- response.Close();
- for (int i = 0; i < _threadNum; i++)
- {
- List<int> range = new List<int>();
- range.Add(i * singelNum);
- if (remainder != 0 && (_threadNum - 1) == i) //剩余的交给最后一个线程
- range.Add(i * singelNum + singelNum + remainder - 1);
- else
- range.Add(i * singelNum + singelNum - 1);
- _thread[i] = new Thread(() => { Download(range[0], range[1]); });
- _thread[i].Name = string.Format("Thread {0}", i + 1);
- _thread[i].Start();
- }
- }
- private void Download(int from, int to)
- {
- Stream httpFileStream = null, localFileStram = null;
- try
- {
- string tmpFileBlock = string.Format(@"{0}\{1}_{2}.dat", _savePath, _fileName, Thread.CurrentThread.Name);
- _tempFiles.Add(tmpFileBlock);
- HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(_fileUrl);
- httprequest.AddRange(from, to);
- HttpWebResponse httpresponse = (HttpWebResponse)httprequest.GetResponse();
- httpFileStream = httpresponse.GetResponseStream();
- localFileStram = new FileStream(tmpFileBlock, FileMode.Create);
- byte[] by = new byte[5000];
- int getByteSize = httpFileStream.Read(by, 0, (int)by.Length); //Read方法将返回读入by变量中的总字节数
- while (getByteSize > 0)
- {
- Thread.Sleep(20);
- _downloadSize += getByteSize;
- localFileStram.Write(by, 0, getByteSize);
- getByteSize = httpFileStream.Read(by, 0, (int)by.Length);
- }
- _threadCompleteNum++;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message.ToString());
- }
- finally
- {
- if (httpFileStream != null) httpFileStream.Dispose();
- if (localFileStram != null) localFileStram.Dispose();
- }
- if (_threadCompleteNum == _threadNum)
- {
- _isComplete = true;
- Complete();
- }
- }
- private void Complete()
- {
- Stream mergeFile = new FileStream(
- string.Format(@"{0}\{1}{2}", _savePath, _fileName, _extName), FileMode.Create);
- BinaryWriter AddWriter = new BinaryWriter(mergeFile);
- foreach (string file in _tempFiles)
- {
- using (FileStream fs = new FileStream(file, FileMode.Open))
- {
- BinaryReader TempReader = new BinaryReader(fs);
- AddWriter.Write(TempReader.ReadBytes((int)fs.Length));
- TempReader.Close();
- }
- File.Delete(file);
- }
- AddWriter.Close();
- }
- }
- }
|