【问题标题】:How To Get The Size Of A File (Hosted On A Web Server)?如何获取文件的大小(托管在 Web 服务器上)?
【发布时间】:2013-01-07 10:33:55
【问题描述】:

我正在使用 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 的情况下获取文件的大小(在下载之前)?

【问题讨论】:

    标签: c# progress-bar webclient filesize


    【解决方案1】:

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

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

    【讨论】:

    • 正是我所做的!谢谢!正如我在上面的评论中所说,每次设置最大值有点草率,而实际上它应该只设置一次。但我想一遍又一遍地设置最大值比使用某种布尔值来知道你第一次进入回调的时间更好。
    • 不建议使用e.ProgressPercentage,尽管它要容易得多
    【解决方案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"]);
    

    【讨论】:

    • 我不确定你的意思。你能详细说明一下吗?看起来你正在设置一些东西,而我认为你需要从标题中读取一些东西?
    • 其实我刚刚发现了一些东西。在回调 webClient_DownloadProgressChanged 中,参数 e 有一个名为 TotalBytesToReceive 的属性。因此,我所要做的就是在第一次进入回调时设置进度条的最大值。或者我可以只是懒惰并在每次调用回调时设置最大值。这将消除我需要某种布尔值来知道这是我第一次进入回调的需要(这对我来说是骇人听闻的)。
    • Sorry Trikks 我接受了 Arun 的回答,因为他完全推荐了我想出的解决方案。不过感谢您的努力!
    【解决方案3】:

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

    // progressBar.Max is always set to 100
    progressBar.Value = e.ProgressPercentage;
    

    【讨论】:

      猜你喜欢
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      相关资源
      最近更新 更多