views:

129

answers:

3

Alright, I have ran into a problem when using DownloadDataAsync and having it return the bytes to me. This 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 =".

A: 

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.

Danny Chen
A: 

DownloadDataAsync returns void so you can't assign it to byte array. To access the downloaded bytes you need to subscribe to DownloadDataCompleted event.

Giorgi
+2  A: 

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
}
Thomas Levesque