Files
MSEssentials.Extensions/MSEssentials.Extensions/HttpClientExtensions.cs
Mateusz Skoczek 4218851796
All checks were successful
Build and publish package / Build (push) Successful in 18s
Build and publish package / Determine version (push) Successful in 20s
Build and publish package / Pack (push) Successful in 19s
Build and publish package / Publish (push) Successful in 14s
rename
2026-04-15 22:47:59 +02:00

33 lines
1.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MSEssentials.Extensions
{
public static class HttpClientExtensions
{
public static async Task DownloadAsync(this HttpClient client, string requestUri, Stream destination, CancellationToken cancellationToken = default, IProgress<double> progress = null)
{
using (HttpResponseMessage response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead))
{
long? contentLength = response.Content.Headers.ContentLength;
await using (Stream download = await response.Content.ReadAsStreamAsync(cancellationToken))
{
if (progress == null || !contentLength.HasValue)
{
await download.CopyToAsync(destination);
return;
}
var relativeProgress = new Progress<long>(totalBytes => progress.Report((double)totalBytes * 100 / contentLength.Value));
await download.CopyToAsync(destination, 81920, relativeProgress, cancellationToken);
progress.Report(100);
}
}
}
}
}