Skip to content
Open
80 changes: 80 additions & 0 deletions Client/FluentClientExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,86 @@ public static IRequest WithOptions(this IRequest request, bool? ignoreHttpErrors
});
}

/// <summary>Download a resource to a file path, reporting incremental download progress if requested.</summary>
/// <param name="client">The HTTP client.</param>
/// <param name="resource">The resource to download.</param>
/// <param name="path">The path to save the downloaded file.</param>
/// <param name="bufferSize">The buffer size to use when reading the response stream.</param>
/// <param name="progress">An optional progress reporter, which receives incremental progress updates (from 0 to 100) as it downloads.</param>
/// <param name="cancellationToken">A cancellation token.</param>
public static async Task DownloadFileAsync(this IClient client, string resource, string path, int bufferSize = 4096, IProgress<double>? progress = null, CancellationToken cancellationToken = default)
{
// fetch response
IResponse response = await client
.GetAsync(resource)
.WithOptions(completeWhen: HttpCompletionOption.ResponseHeadersRead)
.WithCancellationToken(cancellationToken)
.AsResponse()
.ConfigureAwait(false);

// get content length if possible
long contentLength = response.Message.Content.Headers.ContentLength ?? 0;

// init file
using Stream responseStream = await response.AsStream().ConfigureAwait(false);
using FileStream fileStream = File.Create(path, bufferSize);

// stream file to disk
double lastReportedProgress = 0;
{
int bytesRead;
long totalBytesRead = 0L;

long lastTickReported = 0;
const long throttleMilliseconds = 250;

#if NET5_0_OR_GREATER
Memory<byte> buffer = new byte[bufferSize];
while ((bytesRead = await responseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
#else
byte[] buffer = new byte[bufferSize];
while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0)
#endif
{
// stream next chunk
#if NET5_0_OR_GREATER
await fileStream.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
#else
await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
#endif
totalBytesRead += bytesRead;

// get current tick
long tick =
#if NET5_0_OR_GREATER
Environment.TickCount64;
#else
Environment.TickCount;
#endif
if (tick < lastTickReported)
lastTickReported = tick; // workaround: `Environment.TickCount` eventually wraps around, which would stop any further progress updates

// notify progress tracker
if (contentLength > 0 && tick >= lastTickReported + throttleMilliseconds)

@Jericho Jericho Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than throttling progress to once per arbitrary period of 250 ticks, go back to the previous logic and convert percentDownloaded and lastReportedProgress variables to int. The line if (percentDownloaded > lastReportedProgress) will ensure we report progress at most once per percent for a total maximum of 100 progress reports per download. That would keep the logic simple AND prevent overwhelming.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something like this:

        // stream file to disk
        int lastReportedProgress = 0;

        int bytesRead;
        long totalBytesRead = 0L;
        byte[] buffer = new byte[bufferSize];

        while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0)
        {
            // stream next chunk
            await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
            totalBytesRead += bytesRead;

            // notify progress tracker
            if (contentLength > 0)
            {
                // Math.Min is used to avoid reporting more than 100%
                int percentDownloaded = Math.Min((int)((totalBytesRead / (contentLength * 1d)) * 100), 100);

                // report progress if percentage has increased since the last report (to avoid flooding the progress reporter with updates)
                if (percentDownloaded > lastReportedProgress)
                {
                    progress?.Report(percentDownloaded);
                    lastReportedProgress = percentDownloaded;
                }
            }
        }

        // send final progress update
        if (lastReportedProgress < 100)
            progress?.Report(100);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One more thing: if you accept my suggestion, you can also change the progress reporter to:

IProgress<int>? progress = null

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would be elegant, but it'd cause the opposite problem: downloading a large file over a slow connection could go a long time between progress updates, so a stalled download would be indistinguishable from a slow one. With time throttling, slow and fast connections both get regular updates. The throttle could maybe be configurable though.

{
double percentDownloaded = (totalBytesRead / (contentLength * 1d)) * 100;
if (percentDownloaded > 100)
percentDownloaded = 100;

if (percentDownloaded > lastReportedProgress)
{
progress?.Report(percentDownloaded);
lastReportedProgress = percentDownloaded;
lastTickReported = tick;
}
}
}
}

// send final progress update
if (lastReportedProgress < 100)
progress?.Report(100);
}

/*********
** Internal methods
Expand Down
56 changes: 44 additions & 12 deletions Tests/Integration/IntegrationTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq.Expressions;

#if NET452
using System.Net;
#endif
Expand Down Expand Up @@ -55,11 +57,20 @@ public class IntegrationTests
/*********
** Unit tests
*********/
/// <summary>The setup code to before any tests in the fixture.</summary>
[OneTimeSetUp]
public void OneTimeSetUp()
{
#if NET452
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
#endif
}

[Test(Description = "The client can stream a large file.")]
public async Task StreamLargeFile()
{
// arrange
IClient client = this.ConstructClient("https://proof.ovh.net/");
using IClient client = this.ConstructClient("https://proof.ovh.net/");

// act
Stream result = await client
Expand All @@ -71,15 +82,40 @@ public async Task StreamLargeFile()
Assert.IsNotNull(result);
}

[Test(Description = "The client can download a large file.")]
public async Task DownloadLargeFile()
{
string saveToPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
try
{
// arrange
using IClient client = this.ConstructClient("https://proof.ovh.net/");

// act
bool progressInvoked = false;
double lastProgressReported = 0;
await client.DownloadFileAsync("files/1Mb.dat", saveToPath, 4096, new Progress<double>(percent =>
{
Debug.WriteLine($"Download progress: {percent}%");
progressInvoked = true;
lastProgressReported = percent;
}));

// assert
Assert.IsTrue(progressInvoked);
Assert.AreEqual(100, lastProgressReported);
}
finally
{
File.Delete(saveToPath);
}
}

[Test(Description = "The client can fetch a resource from the English Wikipedia's API.")]
public async Task EnglishWikipedia()
{
#if NET452
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
#endif

// arrange
IClient client = this.ConstructClient("https://en.wikipedia.org/");
using IClient client = this.ConstructClient("https://en.wikipedia.org/");

// act
WikipediaMetadata response = await client
Expand All @@ -94,12 +130,8 @@ public async Task EnglishWikipedia()
[Test(Description = "The client can fetch a resource from the Chinese Wikipedia's API, including proper Unicode handling.")]
public async Task ChineseWikipedia()
{
#if NET452
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
#endif

// arrange
IClient client = this.ConstructClient("https://zh.wikipedia.org/");
using IClient client = this.ConstructClient("https://zh.wikipedia.org/");

// act
WikipediaMetadata response = await client
Expand Down Expand Up @@ -165,4 +197,4 @@ public static TObject AssertValue<TObject, TValue>(this TObject obj, Expression<
Assert.AreEqual(expected, actual.Compile().Invoke(obj), "Unexpected value for " + actual.Body);
return obj;
}
}
}