使用 WebClient() 计算要下载的总字节数 [英] Calculating total bytes to download using WebClient()

查看:52
本文介绍了使用 WebClient() 计算要下载的总字节数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量totalBytes"始终为 -1,因此我无法正确计算/更新进度条,为什么会发生这种情况?

The variable 'totalBytes' is constantly at -1 so I cannot calculate/update the progress bar correctly, why would this be happening?

private void button1_Click(object sender, EventArgs e)
{
    WebClient client = new WebClient();
    client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
    client.DownloadFileAsync(new Uri("http://example.com/test.mp3"), @"E:\Test.mp3");
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    double bytesIn = double.Parse(e.BytesReceived.ToString());
    label1.Text = Convert.ToString(bytesIn);

    double totalBytes = double.Parse(e.TotalBytesToReceive.ToString()); //stays at -1
    label2.Text = Convert.ToString(totalBytes);

    double percentage = bytesIn / totalBytes * 100;
    label3.Text = Convert.ToString(percentage);

    progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}

推荐答案

A WebClient 在内部使用了一个 WebRequest,问题很可能是你下载的服务器文件来自不发送 Content-Length HTTP 标头,在这种情况下,您应该使用 Indeterminate ProgressBar 样式(例如 Marquee).

A WebClient uses a WebRequest internally, and the problem is likely that the server you are downloading the file from is not sending the Content-Length HTTP header, in which case you should use a Indeterminate ProgressBar style (eg. Marquee).

这篇关于使用 WebClient() 计算要下载的总字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆