使用WebClient实现文件下载
标签:
杂谈 |
分类: c#方面的总结 |
- using
System; - using
System.Collections.Generic; - using
System.ComponentModel; - using
System.Data; - using
System.Drawing; - using
System.Text; - using
System.Windows.Forms; - using
System.Net; - using
System.IO; - namespace
wiindowsFormsApplication - {
-
publicpartial classForm1 : Form -
{ -
publicForm1() -
{ -
InitializeComponent(); -
this.textBox1.Text= "http://dl-sh-ocn-1.pchome.net/0d/bx/koomail50b8.rar";@ -
} -
newWebClient webClient = WebClient(); -
privatevoid btn_down_Click( objectsender, EventArgs e) -
{ -
-
if(webClient.IsBusy) //是否存在正在进行中的Web请求 -
{ -
webClient.CancelAsync(); -
} -
//为webClient添加事件 -
newwebClient.DownloadProgressChanged += DownloadProgressChangedE ventHandler(webClient_DownloadProgressChanged); -
newwebClient.DownloadFileCompleted+= AsyncCompletedEventHandl er(webClient_DownloadFileCompleted); -
//开始下载 -
newwebClient.DownloadFileAsync( Uri( this.textBox1.Text),"aa.rar"); -
} -
-
privatevoid webClient_DownloadProgressChanged( objectsender, DownloadProgressChangedE ventArgs e) -
{ -
this.progressBar1.Value= e.ProgressPercentage; -
this.lbl_pro.Text= "%";e.ProgressPercentage.ToString() + -
this.lbl_detail.Text= string.Format("正在下载文件,完成进度{0}/{1}(字节)" -
,e.BytesReceived -
,e.TotalBytesToReceive); -
} -
privatevoid webClient_DownloadFileCompleted( objectsender, AsyncCompletedEventArgs e) -
{ -
if(e.Cancelled) -
"下载被取消!");MessageBox.Show( -
else -
"下载完成!");MessageBox.Show( -
} -
privatevoid btn_cancel_Click( objectsender, EventArgs e) -
{ -
this.webClient.CancelAsync(); -
this.webClient.Dispose(); -
} -
} - }
运行界面:

加载中…