Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce memory footprint while downloading a file with HTTPCLient [duplicate]

I was wondering if there's a way I can avoid of getting all the buffer, then writing them to a file using HttpClient and File.WriteAllBytes.

Here's the code snippet I use

public async Task<byte[]> DownloadAsByteArray(string filename)
{
    _logger.LogDebug($"Start downloading {filename} file at {DateTime.Now}");
    
    var result = await _httpClient.GetByteArrayAsync(filename);
    
    return result;
}
var bytes = await _downloadFileService.DownloadAsByteArray(fileDownload);

await File.WriteAllBytesAsync(fullFlePathName, bytes);

For quite huge file, the application memory grows really fast.

like image 949
advapi Avatar asked Dec 05 '25 14:12

advapi


1 Answers

How about using GetAsync instead of GetByteArrayAsync and using Content's CopyTo?

var response = await _httpClient.GetAsync(uri);
using var fs = new FileStream(...);
await response.Content.CopyToAsync(fs);

Or using GetStreamAsync

using var responseStream = await _httpClient.GetStreamAsync(uri);
using var fs = new FileStream(...);
await responseStream.CopyToAsync(fs);
like image 122
Peter Csala Avatar answered Dec 07 '25 04:12

Peter Csala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!