[英]How To Get The Size Of A File (Hosted On A Web Server)?
I am using the WebClient
class to download an .exe file from a web server. 我正在使用
WebClient
类从Web服务器下载.exe文件。 Here is the code I am using to download the file: 这是我用来下载文件的代码:
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadDataAsync(new Uri("http://www.blah.com/calc.exe"));
My application has a ProgressBar which gets updated in the callback ( webClient_DownloadProgressChanged
): 我的应用程序有一个ProgressBar,它在回调中更新(
webClient_DownloadProgressChanged
):
private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = (int)e.BytesReceived;
}
The problem I am having is I have to set the Maximum
value for the progress bar dynamically. 我遇到的问题是我必须动态设置进度条的
Maximum
。 In other words I need to know the size of the file I am downloading before the download starts. 换句话说,我需要知道下载开始之前我正在下载的文件的大小。
Is there a way to get the size of a file (before downloading it) given it's uri? 有没有办法获得文件的大小(在下载之前),因为它是uri?
Try to set max size to e.TotalBytesToReceive like this 尝试将max size设置为e.TotalBytesToReceive,如下所示
private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Max = (int)e.TotalBytesToReceive;
progressBar.Value = (int)e.BytesReceived;
}
One of the ways will be checking for the Content-Length or the Range header in ResponseHeaders. 其中一种方法是检查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"]);
If you only need to update progress bar correctly, the easiest way is to use ProgressPercentage
如果您只需要正确更新进度条,最简单的方法是使用
ProgressPercentage
// progressBar.Max is always set to 100
progressBar.Value = e.ProgressPercentage;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.