webclient下载文件 带进度条
生活随笔
收集整理的這篇文章主要介紹了
webclient下载文件 带进度条
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
private void button1_Click(object sender, EventArgs e){doDownload(textBox1.Text.Trim());}private DateTime StartTime;private void doDownload(string url,string fileName=""){label1.Text = "正在下載:" + url;//label框提示下載文件if (fileName.Length==0){fileName = url.Substring(url.LastIndexOf("/") + 1);}StartTime = DateTime.Now;progressBar1.Value = 0;//初始化單個文件下載條WebClient ws = new WebClient();ws.DownloadProgressChanged += OnDownloadProgressChanged;//綁定下載事件,以便于顯示當前進度ws.DownloadFileCompleted += OnDownloadFileCompleted;//綁定下載完成事件,以便于計算總進度ws.DownloadFileAsync(new Uri(url), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName));//調用DownloadFileAsync方法下載文件//DownloadFileAsync有2個重載,另一個我沒搞明白最后一個參數該傳什么,有哪位朋友知道的,請留言告訴我謝謝//upapp是我一個實體類,UpdateURL存放了下載的地址(值為http://www.harde.com.cn/SoftUpdate/)//Path.Combine()是一個用來連接地址的方法,我將在另一日志中詳細對其介紹}/// 下載進程變更事件private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e){//在網上看到有朋友這么來控制進度條,我覺得麻煩,畢竟有省事的為什么我要麻煩一番……//this.SetProcessBar(e.ProgressPercentage, (int)((nDownloadedTotal + e.BytesReceived) * 100 / total));progressBar1.Value = e.ProgressPercentage;var s = (DateTime.Now - StartTime).TotalSeconds;var sd = ReadableFilesize(e.BytesReceived/s);label1.Text = "下載速度"+sd+"/秒"+",已下載" + ReadableFilesize(e.BytesReceived) + "/總計" + ReadableFilesize(e.TotalBytesToReceive) ;//一個label框,用來顯示當前下載的數據}/// 下載進程變更事件private void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e){MessageBox.Show("complied!");}private string ReadableFilesize(double size){String[] units = { "B", "KB", "MB", "GB", "TB", "PB" };double mod = 1024.0;int i = 0;while (size >= mod){size /= mod;i++;}return Math.Round(size) + units[i];}
總結
以上是生活随笔為你收集整理的webclient下载文件 带进度条的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Kerberos验证过程
- 下一篇: 24个很赞的 Node.js 免费教程和