WebClient DownloadFile displaying wrong percentage

。_饼干妹妹 提交于 2019-12-11 03:59:19

问题


I'm using a System.Net.WebClient to download a file asynchron in my application. For some reason, on some systems the percentage gets wrong calculated.

My (updated) DownloadProgressChanged event:

WebClient client = new WebClient();
client.DownloadProgressChanged += (_sender, _e) => {
    double bytesIn = _e.BytesReceived;
    double totalBytes = _e.TotalBytesToReceive;
    double percentage = bytesIn / totalBytes * 100;
    UpdateConnectingStatus("Missionsdatei wird heruntergeladen... (" + Math.Truncate(percentage).ToString() + "%)");
};

How it should look like (Windows 8.1 64bit):

How it looks on some systems (Windows 7 64bit):

Could it have something to do with the OS? Or any other ideas?

UPDATE: I removed the division (/ 1000000) completly, but it doesn't work either on the same system.

UPDATE 2: I checked the value of totalBytes. The result of totalBytes is -1 on the system where it doesnt work. Any ideas why this is so?

UPDATE 3: I still don't have a solution although I tried to remove the string conversion stuff and adding a .0 to the division. I think it depends on the slow internet connection the person has, at whom it doesn't work.. I now only display the percentage, if it is positive.


回答1:


According to some web searching and according to my decompiler TotalBytesToReceive can be -1 if the size of the download is not (yet) known. (Yes, this is hideous API design.)

Guard for the -1 case:

if (TotalBytesToReceive == -1)
 Print("Download in Progress");
else
 Print(e.ProgressPercent);

It is unclear yet why the download size is not known on that one machine. Maybe there is an HTTP proxy removing the Content-Length header, or the web server is not sending it for some reason.



来源:https://stackoverflow.com/questions/31226077/webclient-downloadfile-displaying-wrong-percentage

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