我已经浏览过网络,无法看到其他人遇到此问题。我使用的是使用DownloadFileAsync的Web客户端,当调用事件处理程序(DownloadProgressChanged)时,由于某种原因,TotalBytesToReceive(来自DownloadProgressChangedArgs)等于-1,从而阻止我使用进度条。我正在检测< 0,如果是这样的话,现在只需要猜100meg,就可以了解它。
然而,BytesRecieved正在工作,文件实际上正在下载,并且AsynCompletedEventHadnler似乎被调用,因此它知道它已完成(因此必须以某种方式知道TotalBytesToReceive?)。 我使用具有凭据和代理凭据的WebClient从通过内部网络的密码保护外部站点下载(因此需要两者) - 不确定这是否会产生任何影响。我以前使用WebClient.DownloadData获取字节数据并将其单独保存并将其放入后台工作程序中,并且工作正常(如果速度很慢)但我无法以这种方式显示进度。此外,DownloadFileAsync似乎为我做了所有这些,因此节省了大量代码。
private void DLFile_AsyncWithStatus(string DLlocation, string un, string pw, string destLoc)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(un, pw); // website login
wc.Proxy.Credentials = new NetworkCredential(ProxyUsername, ProxyPassword, ProxyDomain); //proxy login
Uri uri = new Uri(DLlocation);
// Specify that the DownloadFileCallback method gets called when the download completes.
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(DLFile_AsynWithStatus_Completed);
// Specify a progress notification handler.
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
try
{
wc.DownloadFileAsync(uri, destLoc);
}
catch (WebException e)
{
MessageBox.Show(e.Message);
}
}
private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
if (totalBytes < 0) {
totalBytes = 100.0 * 1000000.0; //guess 100 meg since it is not detecting total bytes
}
double percentage = bytesIn / totalBytes * 100;
lblTmpStatus.Text = "Downloaded " + e.BytesReceived + " of " + e.TotalBytesToReceive;
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}
void DLFile_AsynWithStatus_Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
Msg(e.Error.Message);
}
else
{
progressBar1.Value = 100;//temp.. finish it off incase was less than 100 meg.
}
}