欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c# http下载 例子

程序员文章站 2023-12-30 11:42:04
参考链接: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# http下载 例子

 

上一篇:

下一篇: