WebClient DownloadFileAsync - 如何向用户显示下载速度?

时间:2012-07-17 12:36:12

标签: c# webclient

这几乎是标题中的整个问题。我有一个WPF C#Windows应用程序,我为用户下载文件,现在想显示速度。

4 个答案:

答案 0 :(得分: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变量做任何你需要的事。

答案 1 :(得分:1)

我们可以通过确定自下载开始以来经过了多少秒来轻松完成此操作。我们可以将BytesReceived值除以总秒数来获得速度。看看下面的代码。

base64String = "data:image/jpeg;base64......";

var stringLength = base64String.length - 'data:image/png;base64,'.length;

var sizeInBytes = 4 * Math.ceil((stringLength / 3))*0.5624896334383812;
var sizeInKb=sizeInBytes/1000;

答案 2 :(得分: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);
}

答案 3 :(得分:0)

当您连接WebClient时,您可以加入ProgressChanged事件,例如

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

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