使用WebClient下载文件,但能够在vb.net中获取下载信息

时间:2009-10-23 02:02:13

标签: vb.net webclient

Imports System.Net
Public Class DownloadStuff
    Dim downloader As New WebClient()
    Private Sub Progress_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Progress.Validated
        AddHandler downloader.DownloadProgressChanged, AddressOf DownloadChangedHandler

        Dim uri As New Uri("http://www.example.com/example.txt")
        downloader.DownloadFileAsync(uri, "C:\example.txt")
    End Sub
    Private Sub DownloadChangedHandler(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
        Progress.Maximum = CInt(e.TotalBytesToReceive)
        Progress.Value = CInt(e.BytesReceived)
        Application.DoEvents()
    End Sub
End Class

这是我的代码,但是DownloadProgressChanged事件永远不会被触发。 (我在这里使用示例网址,但它是基本相同的东西)

我做错了什么? Progress是ProgressBar。

这是在VB.net。

在MSDN上,他们提到了一些关于覆盖GetWebRequest的内容,但我不知道如何做或者做什么。

更新:仍然没有进展,我根本无法弄清楚如何使处理程序解雇。

1 个答案:

答案 0 :(得分:1)

试试这个:

Sub Main()

    Dim client As WebClient = New WebClient()
    AddHandler client.DownloadProgressChanged, AddressOf DownloadProgressCallback
    client.DownloadFileAsync(New Uri("..."), "data.txt")

End Sub

Private Sub DownloadProgressCallback( _
    ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)

    Console.WriteLine(e.ProgressPercentage)

End Sub

每当我看到AddHandlerHandles时,我都会感到头晕。