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
try9

{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
}
本文介绍了一种使用C#从指定URL下载文件到本地的方法。该方法通过HttpWebRequest获取资源,并将其保存到指定路径,同时支持进度显示。如果目标文件夹不存在,则会自动创建。
995

被折叠的 条评论
为什么被折叠?



