下载进度条的实现
在wpf中添加一自动更新功能,下载功能已实现,但是下载进度条的显示未实现。
<ProgressBar Name="Prog" Margin="29,72,23,0" Height="27" VerticalAlignment="Top"> </ProgressBar>
/// <summary> /// 下载文件 /// </summary> /// <param name="filename"></param> private void DownLoadFile(string URL, string Filename, ProgressBar pm) { //WebClient wc = new WebClient(); try { //Uri address = new Uri(URL + Filename); //wc.DownloadFile(address, Filename); //从URL地址得到一个WEB请求 System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL + Filename); //从WEB请求得到WEB响应 System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); //从WEB响应得到总字节数 long totalBytes = myrp.ContentLength; //从总字节数得到进度条的最大值 pm.Maximum = (int)totalBytes; //从WEB请求创建流(读) System.IO.Stream st = myrp.GetResponseStream(); //确定下载文件的路径 string DownLoadPath = @"C:\SalesReport\" + Filename; //创建文件流(写) System.IO.Stream so = new System.IO.FileStream(DownLoadPath, System.IO.FileMode.Create); //下载文件大小 long totalDownloadedByte = 0; byte[] by = new byte[1024]; //读流 int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { //更新文件大小 totalDownloadedByte = osize + totalDownloadedByte; //写流 so.Write(by, 0, osize); //更新进度条 pm.Value = (int)totalDownloadedByte; //读流 osize = st.Read(by, 0, (int)by.Length); } //关闭流 so.Close(); //关闭流 st.Close(); } catch (Exception ex) { throw new Exception("下载更新文件出错:" + ex.Message); } }