当前位置 : 主页 > 编程语言 > c语言 >

c# http下载 例子

来源:互联网 收集:自由互联 发布时间:2021-06-25
参考链接:https://www.cnblogs.com/taiyonghai/p/5604159.html 类: /************************************************************************************************************************/ 1 using System; 2 using System.Collections.Ge

参考链接:https://www.cnblogs.com/taiyonghai/p/5604159.html  

类:

/************************************************************************************************************************/

  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.Windows.Forms;
  8 using System.Threading.Tasks;
  9 using System.Threading;
 10 
 11 namespace httpTool
 12 {
 13     class HttpHelper
 14     {
 15         const int bytebuff = 1024;
 16         const int ReadWriteTimeOut = 2 * 1000;//超时等待时间
 17         const int TimeOutWait = 5 * 1000;//超时等待时间
 18         const int MaxTryTime = 12;
 19 
 20         private double totalSize, curReadSize, speed;
 21         private int proc, remainTime;
 22         private int totalTime = 0;
 23 
 24         bool downLoadWorking = false;
 25 
 26         string StrFileName = "";
 27         string StrUrl = "";
 28 
 29         string outMsg = "";
 30 
 31         public HttpHelper(string url, string savePath)
 32         {
 33             this.StrUrl = url;
 34             this.StrFileName = savePath;
 35         }
 36 
 37         /// <summary>
 38         /// 下载数据更新
 39         /// </summary>
 40         /// <param name="totalNum">下载文件总大小</param>
 41         /// <param name="num">已下载文件大小</param>
 42         /// <param name="proc">下载进度百分比</param>
 43         /// <param name="speed">下载速度</param>
 44         /// <param name="remainTime">剩余下载时间</param>
 45         public delegate void delDownFileHandler(string totalNum, string num, int proc, string speed, string remainTime, string outMsg);
 46         public delDownFileHandler processShow;
 47         public delegate void delDownCompleted();
 48         public delDownCompleted processCompleted;
 49         public System.Windows.Forms.Timer timer;
 50 
 51         public void init()
 52         {
 53             timer.Interval = 100;
 54             timer.Tick -= TickEventHandler;
 55             timer.Tick += TickEventHandler;
 56             timer.Enabled = true;
 57             downLoadWorking = true;
 58         }
 59 
 60         /// <summary>
 61         /// 获取文件大小
 62         /// </summary>
 63         /// <param name="size"></param>
 64         /// <returns></returns>
 65         private string GetSize(double size)
 66         {
 67             String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" };
 68             double mod = 1024.0;
 69             int i = 0;
 70             while (size >= mod)
 71             {
 72                 size /= mod;
 73                 i++;
 74             }
 75             return Math.Round(size) + units[i];
 76         }
 77 
 78         /// <summary>
 79         /// 获取时间
 80         /// </summary>
 81         /// <param name="second"></param>
 82         /// <returns></returns>
 83         private string GetTime(int second)
 84         {
 85             return new DateTime(1970, 01, 01, 00, 00, 00).AddSeconds(second).ToString("HH:mm:ss");
 86         }
 87 
 88         /// <summary>
 89         /// 下载文件(同步)  支持断点续传
 90         /// </summary>
 91         public void DowLoadFile()
 92         {
 93             totalSize = GetFileContentLength(StrUrl);
 94 
 95             //打开上次下载的文件或新建文件
 96             long lStartPos = 0;
 97             System.IO.FileStream fs;
 98             if (System.IO.File.Exists(StrFileName))
 99             {
100                 fs = System.IO.File.OpenWrite(StrFileName);
101                 lStartPos = fs.Length;
102                 fs.Seek(lStartPos, System.IO.SeekOrigin.Current);   //移动文件流中的当前指针
103             }
104             else
105             {
106                 fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
107                 lStartPos = 0;
108             }
109 
110             curReadSize = lStartPos;
111 
112             if (curReadSize == totalSize)
113             {
114                 outMsg = "文件已下载!";
115                 processCompleted?.Invoke();
116                 timer.Enabled = false;
117                 return;
118             }
119 
120             //打开网络连接
121             try
122             {
123                 System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
124                 if (lStartPos > 0)
125                     request.AddRange((int)lStartPos);    //设置Range值
126 
127                 //向服务器请求,获得服务器回应数据流
128                 System.IO.Stream ns = request.GetResponse().GetResponseStream();
129                 byte[] nbytes = new byte[bytebuff];
130                 int nReadSize = 0;
131                 proc = 0;
132 
133                 do
134                 {
135 
136                     nReadSize = ns.Read(nbytes, 0, bytebuff);
137                     fs.Write(nbytes, 0, nReadSize);
138 
139                     //已下载大小
140                     curReadSize += nReadSize;
141                     //进度百分比
142                     proc = (int)((curReadSize / totalSize) * 100);
143                     //下载速度
144                     speed = (curReadSize / totalTime) * 10;
145                     //剩余时间
146                     remainTime = (int)((totalSize / speed) - (totalTime / 10));
147 
148                     if (downLoadWorking == false)
149                         break;
150 
151                 } while (nReadSize > 0);
152 
153                 fs.Close();
154                 ns.Close();
155 
156                 if (curReadSize == totalSize)
157                 {
158                     outMsg = "下载完成!";
159                     processCompleted?.Invoke();
160                     downLoadWorking = false;
161                 }
162             }
163             catch (Exception ex)
164             {
165                 fs.Close();
166                 outMsg = string.Format("下载失败:{0}", ex.ToString());
167             }
168         }
169 
170         public void DownLoadPause()
171         {
172             outMsg = "下载已暂停";
173             downLoadWorking = false;
174         }
175 
176         public void DownLoadContinue()
177         {
178             outMsg = "正在下载";
179             downLoadWorking = true;
180             DownLoadStart();
181         }
182 
183         public void DownLoadStart()
184         {
185             Task.Run(() =>
186             {
187                 DowLoadFile();
188             });
189         }
190 
191 
192         /// <summary>
193         /// 定时器方法
194         /// </summary>
195         /// <param name="sender"></param>
196         /// <param name="e"></param>
197         private void TickEventHandler(object sender, EventArgs e)
198         {
199             processShow?.Invoke(GetSize(totalSize),
200                                 GetSize(curReadSize),
201                                 proc,
202                                 string.Format("{0}/s", GetSize(speed)),
203                                 GetTime(remainTime),
204                                 outMsg
205                                 );
206             if (downLoadWorking == true)
207             {
208                 totalTime++;
209             }
210         }
211 
212         /// <summary>
213         /// 获取下载文件长度
214         /// </summary>
215         /// <param name="url"></param>
216         /// <returns></returns>
217         public long GetFileContentLength(string url)
218         {
219             HttpWebRequest request = null;
220             try
221             {
222                 request = (HttpWebRequest)HttpWebRequest.Create(url);
223                 //request.Timeout = TimeOutWait;
224                 //request.ReadWriteTimeout = ReadWriteTimeOut;
225                 //向服务器请求,获得服务器回应数据流
226                 WebResponse respone = request.GetResponse();
227                 request.Abort();
228                 return respone.ContentLength;
229             }
230             catch (Exception e)
231             {
232                 if (request != null)
233                     request.Abort();
234                 return 0;
235             }
236         }
237     }
238 }

 

页面调用

/***************************************************************************************************************/

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 using httpTool;
11 using System.Threading;
12 
13 namespace DownLoadDemo1
14 {
15     public partial class Form1 : Form
16     {
17         static string url = "http://speedtest.dallas.linode.com/100MB-dallas.bin"; //下载地址
18 
19         static string temp = System.Environment.GetEnvironmentVariable("TEMP");
20         static string loadFilefolder = new System.IO.DirectoryInfo(temp).FullName + @"\" + "100MB-dallas.bin";
21 
22         Thread td;
23         HttpHelper httpManager = new HttpHelper(url, loadFilefolder);
24 
25         public Form1()
26         {
27             InitializeComponent();
28         }
29 
30         private void Form1_Load(object sender, EventArgs e)
31         {
32             httpManager.timer = new System.Windows.Forms.Timer();
33             httpManager.processShow += processSho;
34             httpManager.processCompleted += processComplete;
35             httpManager.init();
36 
37         }
38 
39         public void processSho(string totalNum, string num, int proc, string speed, string remainTime, string msg)
40         {
41             this.label1.Text = string.Format("文件大小:{0}", totalNum);
42             this.label2.Text = string.Format("已下载:{0}", num);
43             this.label3.Text = string.Format("进度:{0}%", proc);
44             this.label4.Text = msg;
45             this.label5.Text = string.Format("速度:{0}",speed);
46             this.label6.Text = string.Format("剩余时间:{0}",remainTime);
47         }
48 
49         private void processComplete()
50         {
51             MessageBox.Show("文件下载完成!", "提示");
52         }
53 
54         private void button1_Click(object sender, EventArgs e)
55         {
56             httpManager.DownLoadStart();
57 
58         }
59 
60         private void button2_Click(object sender, EventArgs e)
61         {
62             httpManager.DownLoadPause();
63         }
64 
65         private void button3_Click(object sender, EventArgs e)
66         {
67             httpManager.DownLoadContinue();
68         }
69     }
70 }

效果

/*********************************************************************************/

上一篇:C#读写西门子PLC数据
下一篇:C#:随笔
网友评论