Calculating total bytes to download using WebClient()

笑着哭i 提交于 2019-12-22 11:27:50

问题


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

回答1:


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).




回答2:


You can manually check for the Content-Length in the response headers

client.ResponseHeaders["Content-Length"]


来源:https://stackoverflow.com/questions/10581820/calculating-total-bytes-to-download-using-webclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!