分別是DownloadFile和DownloadFileAsync以及DownloadFileTaskAsync的方法,在這邊就用DownloadFileAsync的方法去做說明
DownloadFileAsync具有兩種方法,分別是DownloadFileAsync(Uri, String)以及DownloadFileAsync(Uri, String, Object),多了Object差異只在userToken,可以參考『WebClient.DownloadFileAsync Method : How to retrieve the Object?』
DownloadFileAsync是一個非同步的方法,透過該方法可以在執行緒透過資源分配的方式去執行
在執行的過程中,可以透過CancelAsync去取消。
DownloadFileAsync會在下載時,觸發DownloadProgressChanged事件,可透過該事件去取得目前的進度
下載完成時會在觸發DownloadFileCompleted事件,可以在該事件內跟使用者說下載完成了
using System;
using System.ComponentModel;
using System.Net;
using System.Windows.Forms;
namespace WebClientDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += ProgressChanged;
client.DownloadFileCompleted += Completed;
client.DownloadFileAsync(new Uri(@"http://downloads.sourceforge.net/project/gnuplot/gnuplot/4.6.3/gp463-win32.zip"), @"gnuplot.zip");
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}
}
}
執行結果:
參考資料:
http://msdn.microsoft.com/zh-tw/library/system.net.webclient.aspx
http://stackoverflow.com/questions/12400841/webclient-downloadfileasync-method-how-to-retrieve-the-object

