/// <summary>
/// 下载文件 ———— 软件更新包
/// </summary>
/// <param name="URL">下载文件地址</param>
/// <param name="filename">存放地址</param>
/// <returns></returns>
public bool DownloadFile(string URL, string filename)
{
float percent = 0;
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//获取请求返回的内容长度
long totalBytes = response.ContentLength;
long totalDownloaded = 0;
byte[] b = new byte[1024];
Stream responseStream = response.GetResponseStream();
//读取字节流
int osize = responseStream.Read(b, 0, b.Length);
FileStream fs = new FileStream(filename, FileMode.Create);
while (osize > 0)
{
totalDownloaded = osize + totalDownloaded;
//为了在加载大量数据时能够有一个数据加载的提示,不至于系统出现假死的现象
//不然label1将由于循环执行太快而来不及显示信息
System.Windows.Forms.Application.DoEvents();
fs.Write(b, 0, osize);
percent = (float)(totalDownloaded / (float)totalBytes) * 100;
osize = responseStream.Read(b, 0, b.Length);
progressBar.Value = (int)percent;
label1.Content = "下载中(" + progressBar.Value + "%)";
System.Windows.Forms.Application.DoEvents();
}
label1.Content = "下载成功!";
label1.Foreground = Brushes.Green;
return true;
}
catch (Exception ex)
{
label1.Content = "下载异常,已停止下载:名称" + URL.Split('_')[1].ToString() + "异常信息:" + ex.Message;
return false;
}
}
WPF 动态进度条
于 2024-03-05 14:37:10 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)