2012-11-23 85 views
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的新手,所以我不能自己寫一些東西,你能給我任何解決方案嗎?

回答

1

我建議不同的東西:你很可能使用DateTime.Now速度給定的開始時間的百分比,它的下載正在算?

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 

因爲它沒有任何意義由接收的字節最後一個塊以確定的速度,而是你衡量字節由總時間的總數和鴻溝。將秒錶實例傳遞給事件處理程序具有以下優點:它不會損壞您的類代碼 - 僅在需要的地方纔可見。

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"; 
+0

謝謝您的回覆。我在哪裏分配這個活動? 'client.DownloadProgressChanged + = Function(sender,e)progressChanged(e.BytesReceived)' – Scott

+0

AddHandler client.DownloadProgressChanged,Sub(s,ee) ProgressChanged(ee.BytesReceived) End Sub - - 聲明您的WebClient變量。 – Ric

+0

@Ric錯誤'聲明期望結束.'然後出現 – Scott

0

這會給你在同一時間的百分比。

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 
+0

提供的其他答案需要從這裏引用(有些部分轉換爲vb:http://stackoverflow.com/questions/11522577/webclient-downloadfileasync-how-can-i-display-download-speed-to-the-user – Ric

0

試試這個:

試試這個只有當你通過一個BackgroundWorker

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 

對不起,我沒有使用正確的格式下載,但是這本身就是一種解決方案。