3

我正在使用WebClient该类从 Web 服务器下载 .exe 文件。这是我用来下载文件的代码:

WebClient webClient = new WebClient();    
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadDataAsync(new Uri("http://www.blah.com/calc.exe")); 

我的应用程序有一个 ProgressBar,它在回调 ( webClient_DownloadProgressChanged) 中得到更新:

private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    progressBar.Value = (int)e.BytesReceived;
}

我遇到的问题是我必须Maximum动态设置进度条的值。换句话说,我需要在下载开始之前知道我正在下载的文件的大小。

有没有办法在给定 uri 的情况下获取文件的大小(在下载之前)?

4

3 回答 3

5

尝试像这样将最大大小设置为 e.TotalBytesToReceive

private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
     progressBar.Max = (int)e.TotalBytesToReceive;
    progressBar.Value = (int)e.BytesReceived;

}
于 2013-01-07T10:43:14.103 回答
2

其中一种方法是检查 ResponseHeaders 中的 Content-Length 或 Range 标头。

// To set the range
//webClient.Headers.Add("Range","bytes=-128");

// To read Content-Length
var bytes = Convert.ToInt64(webClient.ResponseHeaders["Content-Length"]);
于 2013-01-07T10:38:05.533 回答
2

如果只需要正确更新进度条,最简单的方法是使用ProgressPercentage

// progressBar.Max is always set to 100
progressBar.Value = e.ProgressPercentage;
于 2014-02-20T15:48:53.733 回答