C#WebClient使用Async并返回数据

好吧,我在使用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事件:

 client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadCompleted); ... private static void DownloadCompleted(Object sender, DownloadDataCompletedEventArgs e) { byte[] bytes = e.Result; // do something with the bytes } 

client.DownloadDataAsync没有返回值。 我想你想得到下载的数据吗? 你可以在完成比赛中得到它。 DownloadProgressChangedEventArgs e ,使用e.Datae.Result 。 对不起,我忘记了确切的财产。

DownloadDataAsync返回void,因此您无法将其分配给字节数组。 要访问下载的字节,您需要订阅DownloadDataCompleted事件。