我正在使用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,有没有办法获取文件的大小(下载之前)?

最佳答案

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

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

}

07-24 09:48
查看更多