HttpWebRequest下载文件带进度条
Code
1/**//// <summary>
2 /// 下载文件到本地
3 /// </summary>
4 /// <param name="url"></param>
5 /// <param name="filePath"></param>
6 public static void DownloadFile(string url, string localPath, ProgressBar bar)
7 {
8 try
9 {
10 bar.Value = bar.Minimum;
11
12 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
13 HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
14
15 long totalBytes = resp.ContentLength;
16 bar.Maximum = (int)totalBytes;
17
18 using (Stream sResp = resp.GetResponseStream())
19 {
20 if (!Directory.Exists(localPath.Substring(0, localPath.LastIndexOf('\\'))))
21 Directory.CreateDirectory(localPath.Substring(0, localPath.LastIndexOf('\\')));
22 using (Stream sFile = new FileStream(localPath, FileMode.Create))
23 {
24 long totalDownloadBytes = 0;
25 byte[] bs = new byte[1024];
26 int size = sResp.Read(bs, 0, bs.Length);
27 while (size > 0)
28 {
29 totalDownloadBytes += size;
30 App.DoEvents();
31 sFile.Write(bs, 0, size);
32 bar.Value = (int)totalDownloadBytes;
33 size = sResp.Read(bs, 0, bs.Length);
34 }
35 }
36 }
37 bar.Value = bar.Maximum;
38 }
39 catch (Exception ex)
40 {
41 throw ex;
42 }
43 }
1/**//// <summary>
2 /// 下载文件到本地
3 /// </summary>
4 /// <param name="url"></param>
5 /// <param name="filePath"></param>
6 public static void DownloadFile(string url, string localPath, ProgressBar bar)
7 {
8 try
9 {
10 bar.Value = bar.Minimum;
11
12 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
13 HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
14
15 long totalBytes = resp.ContentLength;
16 bar.Maximum = (int)totalBytes;
17
18 using (Stream sResp = resp.GetResponseStream())
19 {
20 if (!Directory.Exists(localPath.Substring(0, localPath.LastIndexOf('\\'))))
21 Directory.CreateDirectory(localPath.Substring(0, localPath.LastIndexOf('\\')));
22 using (Stream sFile = new FileStream(localPath, FileMode.Create))
23 {
24 long totalDownloadBytes = 0;
25 byte[] bs = new byte[1024];
26 int size = sResp.Read(bs, 0, bs.Length);
27 while (size > 0)
28 {
29 totalDownloadBytes += size;
30 App.DoEvents();
31 sFile.Write(bs, 0, size);
32 bar.Value = (int)totalDownloadBytes;
33 size = sResp.Read(bs, 0, bs.Length);
34 }
35 }
36 }
37 bar.Value = bar.Maximum;
38 }
39 catch (Exception ex)
40 {
41 throw ex;
42 }
43 }