C# 使用WebClient()计算要下载的总字节数

C# 使用WebClient()计算要下载的总字节数,c#,winforms,progress-bar,webclient,progress,C#,Winforms,Progress Bar,Webclient,Progress,变量“totalBytes”始终为-1,因此我无法正确计算/更新进度条,为什么会发生这种情况 private void button1_Click(object sender, EventArgs e) { WebClient client = new WebClient(); client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); client.DownloadProgress

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

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());
}

WebClient
在内部使用
WebRequest
,问题可能是您下载文件的服务器没有发送
内容长度
HTTP头,在这种情况下,您应该使用
不确定的
ProgressBar样式(例如Marquee).

您可以手动检查响应标题中的内容长度

client.ResponseHeaders["Content-Length"]

尝试不同的文件Uri(从一些随机网站)。您正在下载的服务器可能没有发送
内容长度
标题,在这种情况下,您可以显示一个不确定的进度条。是的,这很有意义,谢谢:)这是问题吗?如果是这样,我可以将我的评论移动到一个答案,这样它就可以被接受,问题就可以被关闭。我相信,使用下载管理器下载文件也会使用一个不确定的进度条,将其移动到一个答案,我会接受:)虽然它与您的问题相关,但为什么您不使用e.ProgressPercentage作为百分比?