This article describes how to use HttpClient to implement a progress bar when downloading files. Since DownloadOperation cannot be used due to certificate handling limitations, another approach is required.
Starting in .Net 4.5, IProgress
// Set up HttpClient using (var client = new HttpClient()) {
<code class="language-csharp">// 带进度报告的文件下载 await client.DownloadAsync(DownloadUrl, file, progress, cancellationToken);</code>
}
The DownloadAsync extension method depends on another extension method for stream replication with progress reporting:
<code class="language-csharp">public static async Task DownloadAsync(this HttpClient client, string requestUri, Stream destination, IProgress<float> progress = null, CancellationToken cancellationToken = default) { // 获取内容长度的标头 using (var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead)) { // 如果不支持,则忽略进度报告 if (progress == null || !response.Content.Headers.ContentLength.HasValue) { await response.Content.ReadAsStreamAsync(cancellationToken).CopyToAsync(destination); return; } // 计算相对进度 var relativeProgress = new Progress<long>(totalBytes => progress.Report((float)totalBytes / response.Content.Headers.ContentLength.Value)); // 带进度报告的下载 await response.Content.ReadAsStreamAsync().CopyToAsync(destination, 81920, relativeProgress, cancellationToken); progress.Report(1); } } public static async Task CopyToAsync(this Stream source, Stream destination, int bufferSize, IProgress<long> progress = null, CancellationToken cancellationToken = default) { var buffer = new byte[bufferSize]; long totalBytesRead = 0; int bytesRead; while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) { await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); totalBytesRead += bytesRead; progress?.Report(totalBytesRead); } }</code>
<code> 通过以上代码,开发者可以轻松地在使用HttpClient下载文件的同时,实现进度条功能,提升用户体验。 需要注意的是,`CopyToAsync` 方法中的 `bufferSize` 参数可以根据实际情况调整,以平衡性能和内存消耗。</code>
The above is the detailed content of How to Implement a Progress Bar with HttpClient During File Downloads?. For more information, please follow other related articles on the PHP Chinese website!