WebClient 下载文件显示错误的百分比 [英] WebClient DownloadFile displaying wrong percentage
问题描述
我正在使用 System.Net.WebClient
在我的应用程序中异步下载文件.出于某种原因,在某些系统上,百分比计算错误.
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.
我的(更新的)DownloadProgressChanged 事件:
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() + "%)");
};
它应该是什么样子(Windows 8.1 64 位):
How it should look like (Windows 8.1 64bit):
它在某些系统上的外观(Windows 7 64 位):
How it looks on some systems (Windows 7 64bit):
会不会跟操作系统有关?或者有什么其他想法?
Could it have something to do with the OS? Or any other ideas?
更新:我完全删除了除法 (/1000000
),但它在同一系统上也不起作用.
UPDATE: I removed the division (/ 1000000
) completly, but it doesn't work either on the same system.
更新 2:我检查了 totalBytes 的值.totalBytes 的结果在它不工作的系统上是 -1.任何想法为什么会这样?
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?
更新 3:尽管我尝试删除字符串转换内容并将 .0
添加到除法中,但我仍然没有解决方案.我认为这取决于该人的互联网连接速度较慢,它对谁不起作用..我现在只显示百分比,如果它是正数.
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.
推荐答案
根据一些网络搜索并根据我的反编译器 TotalBytesToReceive
如果下载的大小不是(还)可以是 -1已知.(是的,这是可怕的 API 设计.)
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.)
-1 情况的保护:
if (TotalBytesToReceive == -1)
Print("Download in Progress");
else
Print(e.ProgressPercent);
目前还不清楚为什么在那台机器上不知道下载大小.也许有一个 HTTP 代理删除了 Content-Length
标头,或者网络服务器由于某种原因没有发送它.
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.
这篇关于WebClient 下载文件显示错误的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!