我正在尝试为我的程序创建一个更新程序,它会自动从网上下载我的程序的最新版本。现在我希望使用进度条完成此过程(因此,当下载进度为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方法,我将无法使用进度条来跟踪下载进度。非常感谢任何帮助: - )
答案 0 :(得分:0)
当你说文件没有下载时,不知道你的意思吗?你得到一个错误/例外?什么都没发生?你有没有放置断点,debug.prints等?
使用VS2012和asyn / 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
在此示例中,来自Web的数据被下载到数组中,但您当然也可以将其写入文件,或者根据数据执行任何操作。
使用示例:
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