代码:
using System; System.Collections.Concurrent; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.IO; System.linq; System.Net; System.Text; System.Text.RegularExpressions; System.Threading; System.Threading.Tasks; System.windows.Forms; Common.Utils; Utils;namespace 爬虫{ public partial class Form1 : Form { #region 变量 /// <summary> /// 已完成字节数 </summary> private long completedCount = 0; 是否完成 bool isCompleted = true 数据块队列 private ConcurrentQueue<MemoryStream> msQueue = new ConcurrentQueue<MemoryStream>(); 下载开始位置 long range = 文件大小 long total = 一段时间内的完成节点数,计算网速用 long unitCount = 上次计时时间,计算网速用 private DateTime lastTime = DateTime.MinValue; 一段时间内的完成字节数,控制网速用 long unitCountForlimit = 上次计时时间,控制网速用 private DateTime lastTimeForlimit = 下载文件sleep时间,控制速度用 int sleepTime = 1; #endregion #region Form1 public Form1() { InitializeComponent(); } #region Form1_Load voID Form1_Load(object sender,EventArgs e) { lblMsg.Text = string.Empty; lblByteMsg.Text = .Empty; lblSpeed.Text = .Empty; } #region Form1_FormClosing voID Form1_FormClosing(#region btnDownload_Click 下载 voID btnDownload_Click(false; btnDownload.Enabled = ; string url = txtUrl.Text.Trim(); string filePath = CreatefilePath(url); #region 下载线程 Thread thread = new Thread(new ThreadStart(() => { int tryTimes = ; while (!httpDownloadfile(url,filePath)) { Thread.Sleep(10000); tryTimes++; LogUtil.Log("请求服务器失败,重新请求" + tryTimes.ToString() + 次"); this.Invoke(new InvokeDelegate(() => { lblMsg.Text = ; })); httpDownloadfile(url,filePath); } })); thread.IsBackground = ; thread.Start(); #endregion #region 保存文件线程 thread = 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(),0,(int)ms.Length); fs.Close(); } completedCount += ms.Length; } if (total != 0 && total == completedCount) { Thread.Sleep(100); isCompleted = ; } Thread.Sleep(); } })); thread.IsBackground = #region 计算网速/进度线程isCompleted) { Thread.Sleep(1000); if (lastTime != DateTime.MinValue) { double sec = DateTime.Now.Subtract(lastTime).TotalSeconds; double speed = unitCount / sec / 1024; try { #region 显示速度 if (speed < ) { { lblSpeed.Text = string.Format({0}KB/S",speed.ToString(0.00)); })); } else { {0}MB/S1024).ToString(#endregion #region 显示进度 string strTotal = (total / 1024 / ") + MB; if (total < 1024 * ) { strTotal = (total / KB; } string completed = (completedCount / if (completedCount < ) { completed = (completedCount / ; } lblMsg.Text = 进度:{0}/{1},completed,strTotal); lblByteMsg.Text = 已下载:{0}\r\n总大小:{1}if (completedCount == total) { MessageBox.Show(完成); } })); #endregion } catch { } lastTime = DateTime.Now; unitCount = ; } } })); thread.IsBackground = #region 限制网速线程if (lastTimeForlimit != DateTime.Now.Subtract(lastTimeForlimit).TotalSeconds; double speed = unitCountForlimit / sec / #region 限速/解除限速 double limitSpeed = ; if (double.TryParse(txtSpeed.Text.Trim(), limitSpeed)) { if (speed > limitSpeed && sleepTime < ) { sleepTime += if (speed < limitSpeed - 10 && sleepTime >= 2) { sleepTime -= ; } } { txtSpeed.Text = 100; })); } { } lastTimeForlimit = DateTime.Now; unitCountForlimit = } #region httpDownloadfile 下载文件 http下载文件 bool httpDownloadfile(string url,1)"> filePath) { if (!file.Exists(filePath)) { { fileInfo fileInfo = 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() httpWebResponse; if (response.ContentLength == range) { 文件已下载; })); return ; } 设置参数 request = WebRequest.Create(url) ; request.AddRange(range); 发送请求并获取相应回应数据 response = request.GetResponse() 直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); total = range + response.ContentLength; completedCount = range; MemoryStream ms = MemoryStream(); byte[] barr = new byte[]; lastTime = DateTime.Now; lastTimeForlimit = DateTime.Now; int size = responseStream.Read(barr,)barr.Length); unitCount += size; unitCountForlimit += size; ms.Write(barr,size); isCompleted) { size = responseStream.Read(barr,1)">)barr.Length); unitCount += size; unitCountForlimit += size; ms.Write(barr,size); if (ms.Length > 102400) { msQueue.Enqueue(ms); ms = MemoryStream(); } if (completedCount + ms.Length == total) { msQueue.Enqueue(ms); ms = MemoryStream(); } Thread.Sleep(sleepTime); } responseStream.Close(); ; } (Exception ex) { LogUtil.LogError(ex.Message + \r\n" + ex.StackTrace); ; } } #region 根据URL生成文件保存路径 string CreatefilePath( url) { string path = Application.StartupPath + \downloadDirectory.Exists(path)) { Directory.CreateDirectory(path); } string filename = Path.Getfilename(url); if (filename.IndexOf(?") > ) { return path + \" + filename.Substring()); } filename; } } } end Form1类}VIEw Code
测试截图:
总结
以上是内存溢出为你收集整理的C#限速下载网络文件全部内容,希望文章能够帮你解决C#限速下载网络文件所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)