好吧,我在使用 DownloadDataAsync 并让它返回字节给我时遇到了问题。这是我正在使用的代码:
private void button1_Click(object sender, EventArgs e)
{
byte[] bytes;
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
bytes = client.DownloadDataAsync(new Uri("http://example.net/file.exe"));
}
}
void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
label1.Text = Math.Round(bytesIn / 1000) + " / " + Math.Round(totalBytes / 1000);
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
if (progressBar1.Value == 100)
{
MessageBox.Show("Download Completed");
button2.Enabled = true;
}
}
我得到的错误是“无法将类型‘void’隐式转换为‘byte[]’”
无论如何,我可以做到这一点并在下载完成后给我字节吗?删除“bytes =”时效果很好。
自从DownloadDataAsync
方法是异步的,它不会立即返回结果。你需要处理DownloadDataCompleted
event :
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadCompleted);
...
private static void DownloadCompleted(Object sender, DownloadDataCompletedEventArgs e)
{
byte[] bytes = e.Result;
// do something with the bytes
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)