C# WebClient Using Async and returning the data
Alright, I have ran into a problem when using DownloadDataAsync and having it return the bytes to me. This 开发者_StackOverflow中文版is the code I am using:
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;
}
}
The error I get is "Cannot implicitly convert type 'void' to 'byte[]'"
Is there anyway I can make this possible and give me the bytes after it is done downloading? It works fine when removing "bytes =".
Since the DownloadDataAsync
method is asynchronous, it doesn't return an immediate result. You need to handle the DownloadDataCompleted
event :
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadCompleted);
...
private static void DownloadCompleted(Object sender, DownloadDataCompletedEventArgs e)
{
byte[] bytes = e.Result;
// do something with the bytes
}
client.DownloadDataAsync
doesn't have a return value. I think you want to get the downloaded data right? you can get it in the finish event. DownloadProgressChangedEventArgs e
, using e.Data
or e.Result
. Sorry I forgot the exact property.
DownloadDataAsync returns void so you can't assign it to byte array. To access the downloaded bytes you need to subscribe to DownloadDataCompleted event.
精彩评论