C#实现多线程下载文件的方法
作者:我心依旧 时间:2022-04-24 10:59:43
本文实例讲述了C#实现多线程下载文件的方法。分享给大家供大家参考。具体实现方法如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Net;
namespace WfpApp
{
public class MultiDownload
{
#region 变量
private int _threadNum; //线程数量
private long _fileSize; //文件大小
private string _fileUrl; //文件地址
private string _fileName; //文件名
private string _savePath; //保存路径
private short _threadCompleteNum; //线程完成数量
private bool _isComplete; //是否完成
private volatile int _downloadSize; //当前下载大小(实时的)
private Thread[] _thread; //线程数组
private List<string> _tempFiles = new List<string>();
private object locker = new object();
#endregion
#region 属性
/// <summary>
/// 文件名
/// </summary>
public string FileName
{
get
{
return _fileName;
}
set
{
_fileName = value;
}
}
/// <summary>
/// 文件大小
/// </summary>
public long FileSize
{
get
{
return _fileSize;
}
}
/// <summary>
/// 当前下载大小(实时的)
/// </summary>
public int DownloadSize
{
get
{
return _downloadSize;
}
}
/// <summary>
/// 是否完成
/// </summary>
public bool IsComplete
{
get
{
return _isComplete;
}
}
/// <summary>
/// 线程数量
/// </summary>
public int ThreadNum
{
get
{
return _threadNum;
}
}
/// <summary>
/// 保存路径
/// </summary>
public string SavePath
{
get
{
return _savePath;
}
set
{
_savePath = value;
}
}
#endregion
/// <summary>
/// 构造函数
/// </summary>
/// <param name="threahNum">线程数量</param>
/// <param name="fileUrl">文件Url路径</param>
/// <param name="savePath">本地保存路径</param>
public MultiDownload(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();
_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);
//下载指定位置的数据
int[] ran = new int[] { range[0], range[1] };
_thread[i] = new Thread(new ParameterizedThreadStart(Download));
_thread[i].Name = System.IO.Path.GetFileNameWithoutExtension(_fileUrl) + "_{0}".Replace("{0}", Convert.ToString(i + 1));
_thread[i].Start(ran);
}
}
private void Download(object obj)
{
Stream httpFileStream = null, localFileStram = null;
try
{
int[] ran = obj as int[];
string tmpFileBlock = System.IO.Path.GetTempPath() + Thread.CurrentThread.Name + ".tmp";
_tempFiles.Add(tmpFileBlock);
HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(_fileUrl);
httprequest.AddRange(ran[0], ran[1]);
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);
lock (locker) _downloadSize += getByteSize;
localFileStram.Write(by, 0, getByteSize);
getByteSize = httpFileStream.Read(by, 0, (int)by.Length);
}
lock (locker) _threadCompleteNum++;
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
if (httpFileStream != null) httpFileStream.Dispose();
if (localFileStram != null) localFileStram.Dispose();
}
if (_threadCompleteNum == _threadNum)
{
Complete();
_isComplete = true;
}
}
/// <summary>
/// 下载完成后合并文件块
/// </summary>
private void Complete()
{
Stream mergeFile = new FileStream(@_savePath, 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();
}
}
}
调用:
string httpUrl = @"http://172.28.98.96/fdimsservice/2.rar";
string saveUrl = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "//" + System.IO.Path.GetFileName(httpUrl);
int threadNumber = 5;
MultiDownload md = new MultiDownload(threadNumber, httpUrl, saveUrl);
md.Start();
希望本文所述对大家的C#程序设计有所帮助。
标签:C#,多线程,下载
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Swagger2配置方式(解决404报错)
2022-08-30 17:21:13
![](https://img.aspxhome.com/file/2023/0/63660_0s.png)
Java数据结构之顺序表的实现
2023-06-22 00:47:26
![](https://img.aspxhome.com/file/2023/8/57418_0s.jpg)
Java二维数组与动态数组ArrayList类详解
2023-07-31 19:53:56
springboot项目以jar包运行的操作方法
2023-11-10 07:47:43
![](https://img.aspxhome.com/file/2023/8/59328_0s.png)
Java代码实现循环队列的示例代码
2023-11-23 23:51:25
![](https://img.aspxhome.com/file/2023/7/59927_0s.jpg)
SpringBoot整合第三方技术的详细步骤
2023-11-29 08:22:48
![](https://img.aspxhome.com/file/2023/7/60777_0s.png)
Java特性队列和栈的堵塞原理解析
2023-10-13 14:15:55
springboot接收别人上传的本地视频实例代码
2023-03-22 01:55:39
三步轻松搭建springMVC框架
2023-02-01 05:38:34
![](https://img.aspxhome.com/file/2023/6/64036_0s.jpg)
Java获取彩色图像中的主色彩的实例代码
2021-10-16 01:09:39
![](https://img.aspxhome.com/file/2023/2/67172_0s.png)
java中超过long范围的超大整数相加算法详解(面试高频)
2022-09-15 11:22:05
![](https://img.aspxhome.com/file/2023/0/61850_0s.png)
Java线程之守护线程(Daemon)用法实例
2023-11-29 09:15:13
SpringBoot上传文件大小受限问题的解决办法
2023-04-19 09:46:16
![](https://img.aspxhome.com/file/2023/9/63629_0s.jpg)
Android 在程序运行时申请权限的实例讲解
2023-08-04 17:35:57
![](https://img.aspxhome.com/file/2023/7/85997_0s.jpg)
Java利用栈实现简易计算器功能
2022-05-08 16:57:25
Java实现调用外部程序的示例代码
2023-11-10 06:43:12
![](https://img.aspxhome.com/file/2023/2/59212_0s.png)
Spring Cloud Config实现分布式配置中心
2022-04-25 16:28:07
Java面试题-实现复杂链表的复制代码分享
2023-11-23 20:05:39
IDEA教程之Activiti插件图文详解
2023-11-14 23:06:45
![](https://img.aspxhome.com/file/2023/6/59726_0s.png)
Java实现读取163邮箱,qq邮箱的邮件内容
2021-09-27 14:26:31
![](https://img.aspxhome.com/file/2023/9/63159_0s.png)