我制作了一个小应用程序,它有助于下载网页的html内容。我做了进度条,我无法使用webclient downloadprogress更改事件处理程序获取任何值或任何更改。 这是我的代码..
private void Window_Loaded(object sender, RoutedEventArgs e)
{
progressBar1.Maximum = 100;
WebClient wb = new WebClient();
wb.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wb_DownloadProgressChanged);
wb.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wb_DownloadStringCompleted);
wb.DownloadStringAsync(new Uri("http://www.google.com"));
}
void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string htmldoc = e.Result;
}
void wb_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
当我运行此代码时,e.progresspercentage始终为0,当下载完成时,它变为100.所以我无法使进度条工作。有人能告诉我这里有什么问题吗? 提前谢谢。
答案 0 :(得分:1)
你不能,DownloadStringAync不会引发DownloadProgressChanged事件。您可以使用DownloadDataAsync代替,然后使用类似System.Text.Encoding,as mentioned here的内容将其翻译为字符串。
答案 1 :(得分:1)
不确定这一点,但我怀疑DownloadXXX方法依赖于预先报告的总大小以报告进度。就像被动FTP下载不会提前报告总下载大小一样,也许google.com网络服务器没有返回相应的标题,表明将在管道中发送的预期字节数。
答案 2 :(得分:0)
根据文档,DownloadStringAsync不报告进度。请参阅WebClient.DownloadProgressChanged Event。
的文档您还想使用
using System.ComponentModel;
client.DownloadStringCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);