使用.net WeClient DownloadFileAsync时如何获得完整的下载大小

时间:2016-01-31 19:35:51

标签: .net webclient

我使用WebClient实例以异步方式将流数据下载到本地文件。对于WebClient,有一个事件DownloadFileCompleted,我可以检查完成下载。但AsyncCompletedEventArgs参数receive无法确定已完成的文件大小。

能否请您建议一种确定下载大小的方法。

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下载线程的总下载大小。

1 个答案:

答案 0 :(得分: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);
    }