C # WebClient Using Async and Returning Data

Well, I ran into a problem when using DownloadDataAsync and returning bytes to it. This is the code I'm 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: "It is not possible to implicitly convert the type" void "to" byte [] ""

Anyway, can I make this possible and give me bytes after it is loaded? It works great when deleting "bytes =".

+3
source share
3 answers

Since the method DownloadDataAsyncis asynchronous, it does not return an immediate result. You need to handle the event DownloadDataCompleted:

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadCompleted);
...


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

client.DownloadDataAsync . , ? . DownloadProgressChangedEventArgs e, e.Data e.Result. , .

0

DownloadDataAsync returns void, so you cannot assign it to a byte array. To access the downloaded bytes, you need to subscribe to the DownloadDataCompleted event.

0
source

Source: https://habr.com/ru/post/1759471/


All Articles