Search code examples
vb.netbitmapwebclientmemorystream

VB.net DownloadDataAsync to MemoryStream not working


I have the following code to load a picture from the internet directly into my picturebox (from memory):

PictureBox1.Image = New Bitmap(New IO.MemoryStream(New Net.WebClient().DownloadData("LINK")))

The problem here is that my application freezes while the WebClient is downloading, so I thought I would use DownloadDataAsync

However, using this code doesnt work at all:

PictureBox1.Image = New Bitmap(New IO.MemoryStream(New Net.WebClient().DownloadDataAsync(New Uri("LINK"))))

It returns the error "Expression does not produce a value"


Solution

  • As the error message states, you cannot simply pass the DownloadDataAsync as MemoryStream parameter, since DownloadDataAsync is a Sub whereas DownloadData is a function returning Bytes().

    In order to use DownloadDataSync, check out sample code below:

    Dim wc As New Net.WebClient()
    AddHandler wc.DownloadDataCompleted, AddressOf DownloadDataCompleted
    AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged ' in case you want to monitor download progress
    
    wc.DownloadDataAsync(New uri("link"))
    

    Below are the event handlers:

    Sub DownloadDataCompleted(sender As Object, e As DownloadDataCompletedEventArgs)
        '  If the request was not canceled and did not throw
        '  an exception, display the resource.
        If e.Cancelled = False AndAlso e.Error Is Nothing Then
    
            PictureBox1.Image =  New Bitmap(New IO.MemoryStream(e.Result))
        End If
    End Sub
    
    Sub DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
        ' show progress using : 
        ' Percent = e.ProgressPercentage
        ' Text = $"{e.BytesReceived} of {e.TotalBytesToReceive}"
    End Sub