c# http下載 例子


參考鏈接: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 }

效果

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM