2012-07-17 44 views

回答

6
mWebClient.DownloadProgressChanged += (sender, e) => progressChanged(e.BytesReceived); 
//... 
DateTime lastUpdate; 
long lastBytes = 0; 

private void progressChanged(long bytes) 
{ 
    if (lastBytes == 0) 
    { 
     lastUpdate = DateTime.Now; 
     lastBytes = bytes; 
     return; 
    } 

    var now = DateTime.Now; 
    var timeSpan = now - lastUpdate; 
    var bytesChange = bytes - lastBytes; 
    var bytesPerSecond = bytesChange/timeSpan.Seconds; 

    lastBytes = bytes; 
    lastUpdate = now; 
} 

然后用bytesPerSecond变量做任何你需要的。

+0

谢谢,这个很好。 – Drahcir 2012-07-17 13:18:48

+1

当lastUpdate在同一秒内时,timeSpan.Seconds为0,这会导致除以零。 – Chris 2014-12-10 15:25:11

0

使用DownloadProgressChanged event

WebClient client = new WebClient(); 
Uri uri = new Uri(address); 

// Specify that the DownloadFileCallback method gets called 
// when the download completes. 
client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2); 
// Specify a progress notification handler. 
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback); 
client.DownloadFileAsync (uri, "serverdata.txt"); 

private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e) 
{ 
    // Displays the operation identifier, and the transfer progress. 
    Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...", 
     (string)e.UserState, 
     e.BytesReceived, 
     e.TotalBytesToReceive, 
     e.ProgressPercentage); 
} 
0

当挂钩的Web客户端,您可以subsribe到ProgressChanged事件,例如

_httpClient = new WebClient(); 
_httpClient.DownloadProgressChanged += DownloadProgressChanged; 
_httpClient.DownloadFileCompleted += DownloadFileCompleted; 
_httpClient.DownloadFileAsync(new Uri(_internalState.Uri), _downloadFile.FullName); 

此处理程序的EventArgs为您提供BytesReceieved和TotalBytesToReceive。使用这些信息,您应该能够确定下载速度并相应地拍摄进度条。