6

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

4

4 回答 4

10
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 变量做任何你需要的事情。

于 2012-07-17T12:59:15.997 回答
2

我们可以通过确定自下载开始以来已经过去了多少秒来轻松做到这一点。我们可以将 BytesReceived 值从总秒数中除以得到速度。看看下面的代码。

DateTime _startedAt;

WebClient webClient = new WebClient();

webClient.DownloadProgressChanged += OnDownloadProgressChanged;

webClient.DownloadFileAsync(new Uri("Download URL"), "Download Path")

private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    if (_startedAt == default(DateTime))
    {
        _startedAt = DateTime.Now;
    }
    else
    {
        var timeSpan = DateTime.Now - _startedAt;
        if (timeSpan.TotalSeconds > 0)
        {
            var bytesPerSecond = e.BytesReceived / (long) timeSpan.TotalSeconds;
        }
    }
}
于 2018-04-10T09:48:25.300 回答
0

使用DownloadProgressChanged 事件

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);
}
于 2012-07-17T12:54:48.900 回答
0

当您连接 WebClient 时,您可以订阅 ProgressChanged 事件,例如

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

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

于 2012-07-17T12:55:13.720 回答