c# - 如何为 Portable HttpClient 实现进度报告

标签 c# portable-class-library dotnet-httpclient

我正在编写一个库,目的是在桌面(.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/

相关文章:

c# - 使用查询或代码

c# - 从一个委托(delegate)转换为另一个委托(delegate)。伪 Actor

c# - 函数分析问题 - Visual Studio 2010 Ultimate

c# - 在针对多平台的 Windows 8.1 可移植类库项目中,NETFX_CORE 的等价物是什么?

c# - 为什么来自 PCL 项目的 DLL 是 x86 程序集?

c# - 通过 Rest c# httpClient 创建 jira 问题

asp.net-core - 无法使用 Ubuntu 20.04 使 Net5 工作(OpenSSL 连接问题)

java - 使用 JIRA 版本 3.12 创建 JIRA 票证

xamarin.android - PCL 上的 TPL 用于 MvvmCross for PCL Profile 78

c# - 使用 HttpClient 发布自定义类型