Created
June 13, 2022 15:11
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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