【问题标题】:VB.net DownloadDataAsync to MemoryStream not workingVB.net DownloadDataAsync 到 MemoryStream 不起作用
【发布时间】:2019-02-23 10:41:41
【问题描述】:

我有以下代码可以将互联网上的图片直接加载到我的图片框(从内存中):

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

这里的问题是我的应用程序在 WebClient 正在下载时冻结,所以我想我会使用DownloadDataAsync

但是,使用此代码根本不起作用:

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

返回错误“表达式不产生值”

【问题讨论】:

标签: vb.net bitmap webclient memorystream


【解决方案1】:

正如错误消息所述,您不能简单地将DownloadDataAsync 作为MemoryStream 参数传递,因为DownloadDataAsync 是一个Sub,而DownloadData 是一个返回Bytes() 的函数。

要使用DownloadDataSync,请查看以下示例代码:

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"))

以下是事件处理程序:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多