Skip to content

Instantly share code, notes, and snippets.

@paulodiogo
Created June 13, 2022 15:11
Show Gist options
  • Save paulodiogo/8bf3451deec15f6a7784b70f888755bc to your computer and use it in GitHub Desktop.
Save paulodiogo/8bf3451deec15f6a7784b70f888755bc to your computer and use it in GitHub Desktop.
Progress while downloading a large file with HttpClient https://github.com/dotnet/runtime/issues/16681
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, <URL>) { };
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStreamAsync();
var size = response?.Content?.Headers?.ContentLength ?? 0;
byte[] fileArray;
byte[] buffer = new byte[16 * 1024];
long total = 0;
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = await content.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await ms.WriteAsync(buffer, 0, read);
if (size > 0)
{
total += read;
Progress = (total / (double)size);
}
}
fileArray = ms.ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment