0

我正在尝试为我的程序创建一个更新程序,它会自动从网上下载我的程序的最新版本。现在我希望使用进度条完成此过程(因此当下载进度为 50% 时,进度条为中途)。这是我的代码:

 Private Sub client_ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
    Dim bytesIn As Double = Double.Parse(e.BytesReceived.ToString())
    Dim totalBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString())
    Dim percentage As Double = bytesIn / totalBytes * 100

    client.Value = Int32.Parse(Math.Truncate(percentage).ToString())
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim url As String = "MY DOWNLOAD LINK"
    'Download
    Dim client As WebClient = New WebClient
    AddHandler client.DownloadProgressChanged, AddressOf client_ProgressChanged
    AddHandler client.DownloadFileCompleted, AddressOf client_DownloadCompleted
    client.DownloadFileAsync(New Uri(url), "C:\Users\User\Desktop\BACKUP\TESTING\New folder\1.exe")
End Sub
End Class

现在我知道保存文件的位置是我手动输入的,但我稍后会更改。我目前的问题是文件没有被下载。但是,当我将 DownloadFileAsync 方法更改为 DownloadFile 时,我的程序会下载该文件。但是,使用 DownloadFile 方法,我将无法使用进度条来跟踪下载进度。任何帮助深表感谢 :-)

4

1 回答 1

0

不知道你的意思,当你说文件没有下载时?你得到一个错误/异常?什么都没有发生?您是否放置了断点、debug.prints 等?

使用 VS2012 和 async/await,您可以将所有内容放入一个方法中,并保持“线性代码流”。导入 System.Threading 和 System.Threading.Tasks

Private Async Function DownloadWithProgress(ByVal url As String, ByVal p As ProgressBar) As Task(Of Integer)

    Dim wc As Net.HttpWebRequest = DirectCast(Net.HttpWebRequest.Create(url), Net.HttpWebRequest)
    Dim resp = Await (New TaskFactory(Of Net.WebResponse)).StartNew(AddressOf wc.GetResponse)
    p.Value = 0
    p.Maximum = CInt(resp.ContentLength)
    Dim rqs = resp.GetResponseStream


    Dim bufsize As Integer = 1 << 16
    Dim buffer(bufsize) As Byte
    Dim got As Integer = 0
    Dim total As Integer = 0
    Do
        got = Await (New TaskFactory(Of Integer)).FromAsync(AddressOf rqs.BeginRead, AddressOf rqs.EndRead, buffer, 0, bufsize, Nothing)
        total += got
        Me.Label1.Text = "got: " & total.ToString
        p.Increment(got)
    Loop Until got = 0

    Return total

End Function

在这个示例中,来自网络的数据被下载到一个数组中,但您当然也可以将其写入一个文件,或者对数据做任何您想做的事情。

使用示例:

Private running As Boolean = False
Private Async Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    If running Then
        MessageBox.Show("Cant you see, I'm working?")
        Exit Sub
    Else
        running = True
    End If

    Await DownloadWithProgress("http://download.thinkbroadband.com/5MB.zip", ProgressBar1)
    running = False

End Sub
于 2013-10-18T21:50:47.260 回答