代码:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common.Utils;
using Utils; namespace 爬虫
{
public partial class Form1 : Form
{
#region 变量
/// <summary>
/// 已完成字节数
/// </summary>
private long completedCount = ;
/// <summary>
/// 是否完成
/// </summary>
private bool isCompleted = true;
/// <summary>
/// 数据块队列
/// </summary>
private ConcurrentQueue<MemoryStream> msQueue = new ConcurrentQueue<MemoryStream>();
/// <summary>
/// 下载开始位置
/// </summary>
private long range = ;
/// <summary>
/// 文件大小
/// </summary>
private long total = ;
/// <summary>
/// 一段时间内的完成节点数,计算网速用
/// </summary>
private long unitCount = ;
/// <summary>
/// 上次计时时间,计算网速用
/// </summary>
private DateTime lastTime = DateTime.MinValue;
/// <summary>
/// 一段时间内的完成字节数,控制网速用
/// </summary>
private long unitCountForLimit = ;
/// <summary>
/// 上次计时时间,控制网速用
/// </summary>
private DateTime lastTimeForLimit = DateTime.MinValue;
/// <summary>
/// 下载文件sleep时间,控制速度用
/// </summary>
private int sleepTime = ;
#endregion #region Form1
public Form1()
{
InitializeComponent();
}
#endregion #region Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
lblMsg.Text = string.Empty;
lblByteMsg.Text = string.Empty;
lblSpeed.Text = string.Empty;
}
#endregion #region Form1_FormClosing
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{ }
#endregion #region btnDownload_Click 下载
private void btnDownload_Click(object sender, EventArgs e)
{
isCompleted = false;
btnDownload.Enabled = false;
string url = txtUrl.Text.Trim();
string filePath = CreateFilePath(url); #region 下载线程
Thread thread = new Thread(new ThreadStart(() =>
{
int tryTimes = ;
while (!HttpDownloadFile(url, filePath))
{
Thread.Sleep(); tryTimes++;
LogUtil.Log("请求服务器失败,重新请求" + tryTimes.ToString() + "次");
this.Invoke(new InvokeDelegate(() =>
{
lblMsg.Text = "请求服务器失败,重新请求" + tryTimes.ToString() + "次";
}));
HttpDownloadFile(url, filePath);
}
}));
thread.IsBackground = true;
thread.Start();
#endregion #region 保存文件线程
thread = new Thread(new ThreadStart(() =>
{
while (!isCompleted)
{
MemoryStream ms;
if (msQueue.TryDequeue(out ms))
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Write))
{
fs.Seek(completedCount, SeekOrigin.Begin);
fs.Write(ms.ToArray(), , (int)ms.Length);
fs.Close();
}
completedCount += ms.Length;
} if (total != && total == completedCount)
{
Thread.Sleep();
isCompleted = true;
} Thread.Sleep();
}
}));
thread.IsBackground = true;
thread.Start();
#endregion #region 计算网速/进度线程
thread = new Thread(new ThreadStart(() =>
{
while (!isCompleted)
{
Thread.Sleep(); if (lastTime != DateTime.MinValue)
{
double sec = DateTime.Now.Subtract(lastTime).TotalSeconds;
double speed = unitCount / sec / ; try
{
#region 显示速度
if (speed < )
{
this.Invoke(new InvokeDelegate(() =>
{
lblSpeed.Text = string.Format("{0}KB/S", speed.ToString("0.00"));
}));
}
else
{
this.Invoke(new InvokeDelegate(() =>
{
lblSpeed.Text = string.Format("{0}MB/S", (speed / ).ToString("0.00"));
}));
}
#endregion #region 显示进度
this.Invoke(new InvokeDelegate(() =>
{
string strTotal = (total / / ).ToString("0.00") + "MB";
if (total < * )
{
strTotal = (total / ).ToString("0.00") + "KB";
}
string completed = (completedCount / / ).ToString("0.00") + "MB";
if (completedCount < * )
{
completed = (completedCount / ).ToString("0.00") + "KB";
}
lblMsg.Text = string.Format("进度:{0}/{1}", completed, strTotal);
lblByteMsg.Text = string.Format("已下载:{0}\r\n总大小:{1}", completedCount, total); if (completedCount == total)
{
MessageBox.Show("完成");
}
}));
#endregion
}
catch { } lastTime = DateTime.Now;
unitCount = ;
}
}
}));
thread.IsBackground = true;
thread.Start();
#endregion #region 限制网速线程
thread = new Thread(new ThreadStart(() =>
{
while (!isCompleted)
{
Thread.Sleep(); if (lastTimeForLimit != DateTime.MinValue)
{
double sec = DateTime.Now.Subtract(lastTimeForLimit).TotalSeconds;
double speed = unitCountForLimit / sec / ; try
{
#region 限速/解除限速
double limitSpeed = ;
if (double.TryParse(txtSpeed.Text.Trim(), out limitSpeed))
{
if (speed > limitSpeed && sleepTime < )
{
sleepTime += ;
}
if (speed < limitSpeed - && sleepTime >= )
{
sleepTime -= ;
}
}
else
{
this.Invoke(new InvokeDelegate(() =>
{
txtSpeed.Text = "";
}));
}
#endregion
}
catch { } lastTimeForLimit = DateTime.Now;
unitCountForLimit = ;
}
}
}));
thread.IsBackground = true;
thread.Start();
#endregion }
#endregion #region HttpDownloadFile 下载文件
/// <summary>
/// Http下载文件
/// </summary>
public bool HttpDownloadFile(string url, string filePath)
{
try
{
if (!File.Exists(filePath))
{
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
fs.Close();
}
}
else
{
FileInfo fileInfo = new FileInfo(filePath);
range = fileInfo.Length;
} // 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)";
request.Proxy = null;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.ContentLength == range)
{
this.Invoke(new InvokeDelegate(() =>
{
lblMsg.Text = "文件已下载";
}));
return true;
} // 设置参数
request = WebRequest.Create(url) as HttpWebRequest;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)";
request.Proxy = null;
request.AddRange(range);
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream(); total = range + response.ContentLength;
completedCount = range; MemoryStream ms = new MemoryStream();
byte[] bArr = new byte[];
lastTime = DateTime.Now;
lastTimeForLimit = DateTime.Now;
int size = responseStream.Read(bArr, , (int)bArr.Length);
unitCount += size;
unitCountForLimit += size;
ms.Write(bArr, , size);
while (!isCompleted)
{
size = responseStream.Read(bArr, , (int)bArr.Length);
unitCount += size;
unitCountForLimit += size;
ms.Write(bArr, , size);
if (ms.Length > )
{
msQueue.Enqueue(ms);
ms = new MemoryStream();
}
if (completedCount + ms.Length == total)
{
msQueue.Enqueue(ms);
ms = new MemoryStream();
} Thread.Sleep(sleepTime);
}
responseStream.Close();
return true;
}
catch (Exception ex)
{
LogUtil.LogError(ex.Message + "\r\n" + ex.StackTrace);
return false;
}
}
#endregion #region 根据URL生成文件保存路径
private string CreateFilePath(string url)
{
string path = Application.StartupPath + "\\download";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
} string fileName = Path.GetFileName(url);
if (fileName.IndexOf("?") > )
{
return path + "\\" + fileName.Substring(, fileName.IndexOf("?"));
}
else
{
return path + "\\" + fileName;
}
}
#endregion } //end Form1类
}

测试截图:

C#限速下载网络文件的更多相关文章

  1. JAVA多线程下载网络文件

    JAVA多线程下载网络文件,开启多个线程,同时下载网络文件.   源码如下:(点击下载 MultiThreadDownload.java) import java.io.InputStream; im ...

  2. Java读取并下载网络文件

      CreateTime--2017年8月21日10:11:07 Author:Marydon import java.io.ByteArrayOutputStream; import java.io ...

  3. python下载网络文件

    python下载网络文件 制作人:全心全意 下载图片 #!/usr/bin/python #-*- coding: utf-8 -*- import requests url = "http ...

  4. DELPHI TDownLoadURL下载网络文件

      DELPHI XE6 FMX 附件:http://files.cnblogs.com/xe2011/IDHttp_fmx.7z unit Unit1; interface uses //引用 Vc ...

  5. 【python】下载网络文件到本地

    # 下载网络图片文件到本地 import urllib.request rsp=urllib.request.urlopen("http://n.sinaimg.cn/ent/transfo ...

  6. java 下载网络文件

    1.FileUtils.copyURLToFile实现: import java.io.File; import java.net.URL; import org.apache.commons.io. ...

  7. python使用wget下载网络文件

    wget是一个从网络上自动下载文件的自由工具.它支持HTTP,HTTPS和FTP协议,可以使用HTTP代理. ubuntu 安装wget pip install wget 从网络或本地硬盘下载文件(并 ...

  8. 解决FTPClient下载网络文件线程挂起问题

    今天在windows上调试FTP下载文件时,出险线程假死,代码如下: if (inputStream != null) { byte[] data = null; ByteArrayOutputStr ...

  9. 网络编程(一):用C#下载网络文件的2种方法

    使用C#下载一个Internet上的文件主要是依靠HttpWebRequest/HttpWebResonse和WebClient.具体处理起来还有同步和异步两种方式,所以我们其实有四种组合. 1.使用 ...

随机推荐

  1. 开发者接入 基本配置 服务器配置 out.aspx

    页面代码: 前段为默认的,什么都不用写,后台如下: 即可 来自为知笔记(Wiz)

  2. 计算机程序的思维逻辑 (60) - 随机读写文件及其应用 - 实现一个简单的KV数据库

    57节介绍了字节流, 58节介绍了字符流,它们都是以流的方式读写文件,流的方式有几个限制: 要么读,要么写,不能同时读和写 不能随机读写,只能从头读到尾,且不能重复读,虽然通过缓冲可以实现部分重读,但 ...

  3. Oracle手边常用70则脚本知识汇总

    Oracle手边常用70则脚本知识汇总 作者:白宁超 时间:2016年3月4日13:58:36 摘要: 日常使用oracle数据库过程中,常用脚本命令莫不是用户和密码.表空间.多表联合.执行语句等常规 ...

  4. EF上下文对象线程内唯一性与优化

    在一次请求中,即一个线程内,若是用到EF数据上下文对象,就创建一个,这也加是很多人的代码中习惯在使用上下文对象时,习惯将对象建立在using中,也是为了尽早释放上下文对象, 但是如果有一个业务逻辑调用 ...

  5. 【Java每日一题】20170105

    20170104问题解析请点击今日问题下方的"[Java每日一题]20170105"查看(问题解析在公众号首发,公众号ID:weknow619) package Jan2017; ...

  6. Configure a bridged network interface for KVM using RHEL 5.4 or later?

    environment Red Hat Enterprise Linux 5.4 or later Red Hat Enterprise Linux 6.0 or later KVM virtual ...

  7. linux基础命令

    系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...

  8. grunt配置任务

    这个指南解释了如何使用 Gruntfile 来为你的项目配置task.如果你还不知道 Gruntfile 是什么,请先阅读 快速入门 指南并看看这个Gruntfile 实例. Grunt配置 Grun ...

  9. 感悟 GNU C 以及将 Vim 打造成 C/C++ 的半自动化 IDE

    C 语言在 Linux 系统中的重要性自然是无与伦比.不可替代,所以我写 Linux 江湖系列不可能不提 C 语言.C 语言是我的启蒙语言,感谢 C 语言带领我进入了程序世界.虽然现在不靠它吃饭,但是 ...

  10. RabbitMQ的安装过程

    原创文章转载请注明出处:@协思, http://zeeman.cnblogs.com 网上一些安装教程都较为繁琐,实际上只需要两个RPM包,几分钟即可完成一台实例部署. 准备下载Erlang包: ht ...