2

变量“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());
}
4

2 回答 2

3

A在内部WebClient使用 a WebRequest,问题可能是您从中下载文件的服务器未发送Content-LengthHTTP 标头,在这种情况下,您应该使用IndeterminateProgressBar 样式(例如 Marquee)。

于 2012-05-14T11:28:10.743 回答
0

您可以手动检查响应标头中的 Content-Length

client.ResponseHeaders["Content-Length"]
于 2012-05-14T12:13:54.373 回答