2016-01-31 20 views
0

我使用WebClient實例將流數據異步下載到本地文件。對於WebClient,有一個事件DownloadFileCompleted,我可以檢查完成的下載。但AsyncCompletedEventArgs參數接收沒有任何方法來確定完成的文件大小。如何在使用.net WeClient時下載文件同步

你可以請我建議一種方法來確定下載的大小。

var webClient = new WebClient(); 
webClient.DownloadFileCompleted += webClient_DownloadFileCompleted; 
webClient.DownloadFileAsync(new Uri(url), localPath); 

    void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) 
{ 
// it seems 'e' arg does not have any useful information related to the download. 
} 

當我使用DownloadProgressChanged事件,甚至100%的百分比下載兩次觸發。所以我無法準確計算不同異步webclient下載線程的總下載大小。

回答

0

我會推薦使用HttpClient和他的異步API。比你可以讀取響應http標題例如內容長度。作爲一個例子,請看下面的代碼。

static void Main(string[] args) 
    { 
     var uri = "http://cdimage.debian.org/debian-cd/8.3.0/amd64/iso-cd/MD5SUMS"; 
     var path = "output.txt"; 
     DownloadFileAsync(uri, path); 
     Console.ReadKey(); 
    } 

    static async void DownloadFileAsync(string uri, string path) 
    { 
     var http = new HttpClient(); 
     var response = await http.GetAsync(uri); 
     Console.WriteLine(response.Content.Headers.ContentLength); 
     using (var responseStream = await response.Content.ReadAsStreamAsync()) 
     using (var localStream = File.Create(path)) 
      responseStream.CopyTo(localStream); 
    }