我正在编写一个库,目的是在桌面(.Net 4.0 及更高版本)、手机(WP 7.5 及更高版本)和 Windows 应用商店(Windows 8 及更高版本)应用程序中使用它。
该库能够使用 Portable HttpClient 库从 Internet 下载文件,并报告下载进度。
我在这里和互联网的其他地方搜索有关如何实现进度报告的文档和代码示例/指南,但这种搜索让我一无所获。
有没有人有文章、文档、指南、代码示例或任何帮助我实现这一目标的东西?
最佳答案
我写了下面的代码来实现进度报告。该代码支持我想要的所有平台;但是,您需要引用以下 NuGet 包:
- Microsoft.Net.Http
- Microsoft.Bcl.Async
代码如下:
public async Task DownloadFileAsync(string url, IProgress<double> progress, CancellationToken token)
{
var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);
if (!response.IsSuccessStatusCode)
{
throw new Exception(string.Format("The request returned with HTTP status code {0}", response.StatusCode));
}
var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L;
var canReportProgress = total != -1 && progress != null;
using (var stream = await response.Content.ReadAsStreamAsync())
{
var totalRead = 0L;
var buffer = new byte[4096];
var isMoreToRead = true;
do
{
token.ThrowIfCancellationRequested();
var read = await stream.ReadAsync(buffer, 0, buffer.Length, token);
if (read == 0)
{
isMoreToRead = false;
}
else
{
var data = new byte[read];
buffer.ToList().CopyTo(0, data, 0, read);
// TODO: put here the code to write the file to disk
totalRead += read;
if (canReportProgress)
{
progress.Report((totalRead * 1d) / (total * 1d) * 100);
}
}
} while (isMoreToRead);
}
}
使用起来很简单:
var progress = new Microsoft.Progress<double>();
progress.ProgressChanged += (sender, value) => System.Console.Write("\r%{0:N0}", value);
var cancellationToken = new CancellationTokenSource();
await DownloadFileAsync("http://www.dotpdn.com/files/Paint.NET.3.5.11.Install.zip", progress, cancellationToken.Token);
关于c# - 如何为 Portable HttpClient 实现进度报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21169573/