[C#]利用WebClient透過Proxy下載檔案,並處理進度更新及下載完成事件
如果沒有要透過Proxy下載檔案,可以將5,6,7,10行拿掉
1: using System.Net;
2:
3: public void Fatch(string url, string fileName)
4: {
5: WebProxy webProxy = new WebProxy(ipString, port);
6: NetworkCredential networkCredential = new NetworkCredential(userNameString, passwordString);
7: webProxy.Credentials = networkCredential;
8:
9: WebClient webClient = new WebClient();
10: webClient.Proxy = webProxy;
11:
12: //處理下載完成事件
13: webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadCompletedCallback);
14: //處理進度更新事件
15: webClient.DownloadProgressChanged +=new DownloadProgressChangedEventHandler(downloadProgressChangedCallback);
16:
17: webClient.DownloadFileAsync(new Uri(url), fileName);
18: }
19:
20: //處理下載完成事件
21: private void downloadCompletedCallback(object sender, AsyncCompletedEventArgs e)
22: {
23: Console.WriteLine("下載完成");
24: }
25:
26:
27: //處理進度更新事件
28: private void downloadProgressChangedCallback(object sender, DownloadProgressChangedEventArgs e)
29: {
30: Console.WriteLine("進度(%) : " + e.ProgressPercentage);
31: Console.WriteLine("進度(bytes) : " + e.BytesReceived +"/" + e.TotalBytesToReceive);
32: }
0 意見:
張貼留言