0

我正在使用以下内容下载文件:

Dim client As WebClient = New WebClient()
client.DownloadFileAsync(New Uri("http://cachefly.cachefly.net/100mb.test"), "C:\Users\Dir\100mb.test")

该文件下载并保存到 中C://Users/Dir/100mb.test,但在下载时我想在标签中显示下载速度。我怎样才能做到这一点?我已经阅读了许多教程,但其中大多数都不起作用或已过时。我是vb.net的新手,所以我不能自己写东西,你能给我任何解决方案吗?

4

4 回答 4

1

我可以建议一些不同的东西吗?

Imports System.Net

Public Class Form1

Private tmp = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Temp, "snafu.fubar")
Private Downloading As Boolean = False

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    If Downloading Then Exit Sub
    Downloading = True

    Dim wc As New WebClient
    AddHandler wc.DownloadProgressChanged, AddressOf wc_ProgressChanged
    AddHandler wc.DownloadFileCompleted, AddressOf wc_DownloadDone

    wc.DownloadFileAsync(New Uri("http://cachefly.cachefly.net/100mb.test"), tmp, Stopwatch.StartNew)

End Sub

Private Sub wc_DownloadDone(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs)
    Downloading = False
End Sub

Private Sub wc_ProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
    Me.Label1.Text = (e.BytesReceived / (DirectCast(e.UserState, Stopwatch).ElapsedMilliseconds / 1000.0#)).ToString("#")
End Sub

End Class

因为通过接收到的最后一个字节块来确定速度是没有意义的,而是您测量字节总数并除以总时间。将秒表实例传递给事件处理程序的优点是它不会“破坏”您的类代码 - 它仅在需要的地方可见。

于 2012-11-23T22:54:31.963 回答
0

定义全局变量:

Dim lastUpdate As DateTime
Dim lastBytes As Long = 0

您需要为进度分配一个事件:

Dim client As WebClient = New WebClient()
client.DownloadFileAsync(New Uri("http://cachefly.cachefly.net/100mb.test"), "C:\Users\Dir\100mb.test")
client.DownloadProgressChanged += Function(sender, e) progressChanged(e.BytesReceived)

事件:

Private Sub progressChanged(bytes As Long)
    If lastBytes = 0 Then
        lastUpdate = DateTime.Now
        lastBytes = bytes
        Return
    End If

    Dim now = DateTime.Now
    Dim timeSpan = now - lastUpdate
    If Not timeSpan.Seconds = 0
         Dim bytesChange = bytes - lastBytes
         Dim bytesPerSecond = bytesChange / timeSpan.Seconds

         lastBytes = bytes
         lastUpdate = now
    End If
End Sub

你有每秒字节数的计算。

label.Text = bytesPerSecond.ToString() + "B/s"; 
于 2012-11-23T15:59:06.557 回答
0

这将同时给你百分比。您可能可以使用 DateTime 从给定开始时间的百分比计算。现在下载的速度:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Try

    Dim client As WebClient = New WebClient()
    AddHandler client.DownloadProgressChanged, AddressOf ProgChanged
    client.DownloadFileAsync(New Uri("http://cachefly.cachefly.net/100mb.test"), "C:\Users\Dir\100mb.test")

Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub ProgChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
        Dim progressPercentage As Integer = e.ProgressPercentage
End Sub
于 2012-11-23T16:00:35.263 回答
0

试试这个:

仅在通过后台工作程序下载时尝试此操作

Private Sub worker_DoWork(Byval sender As Object, Byval e As DoWorkEventArgs)

Dim req As WebRequest = WebRequest.Create(downloadUrl) 'Make a request for the url of the file to be downloaded
Dim resp As WebResponse = req.GetResponse 'Ask for the response
Dim fs As New FileStream(path to download to, FileMode.CreateNew) 'Create a new FileStream that writes to the desired download path

Dim buffer(8192) As Byte 'Make a buffer
Dim downloadedsize As Long = 0
Dim downloadedTime As Long = 0

Dim dlSpeed As Long = 0
Dim currentSize As Long = 0 'Size that has been downloaded
Dim totalSize As Long = req.ContentLength 'Total size of the file that has to be downloaded

  Do While currentSize < totalSize
   Dim read As Integer = resp.GetResponseStream.Read(buffer, 0, 8192) 'Read the buffer from the response the WebRequest gave you

   fs.Write(buffer, 0, read) 'Write to filestream that you declared at the beginning of the DoWork sub

   currentSize += read

   downloadedSize += read
   downloadedTime += 1 'Add 1 millisecond for every cycle the While field makes

   If downloadedTime = 1000 Then 'Then, if downloadedTime reaches 1000 then it will call this part
      dlSpeed = (downloadedSize / TimeSpan.FromMilliseconds(downloadedTime).TotalSeconds) 'Calculate the download speed by dividing the downloadedSize by the total formatted seconds of the downloadedTime

      downloadedTime = 0 'Reset downloadedTime and downloadedSize
      downloadedSize = 0
   End If
  End While

fs.Close() 'Close the FileStream first, or the FileStream will crash.
resp.Close() 'Close the response

End Sub

很抱歉没有使用正确的格式,但这本身就是一个解决方案。

于 2015-09-11T11:02:30.210 回答