Can I directly go from HttpResponseMessage to a file without going through memory?

My program uses HttpClient to send a GET request to the web API, and this returns the file.

Now I use this code (simplified) to store the file on disk:

public async Task<bool> DownloadFile()
{
    var client = new HttpClient();
    var uri = new Uri("http://somedomain.com/path");
    var response = await client.GetAsync(uri);

    if (response.IsSuccessStatusCode)
    {
        var fileName = response.Content.Headers.ContentDisposition.FileName;
        using (var fs = new FileStream("C:\test\" + fileName, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            await response.Content.CopyToAsync(fs);
            return true;
        }
    }

    return false;
}

Now that this code works, the process loads the entire file into memory. In fact, I would prefer that the stream be passed from HttpResponseMessage.Content to FileStream, so that only a small portion of it is stored in memory.

We plan to use this on large files (> 1 GB), so is there a way to achieve this without having the entire file in memory?

Ideally, without manual enumeration by reading the part in bytes [] and writing this part to the file stream until all the content has been written?

+4
1

, - HttpClient.GetAsync(), , :

(, ),

HttpClient.GetStreamAsync(), :

.

, . , -, ( ), HttpWebRequest, ( ..), , - :

public async Task<bool> DownloadFile()
{
    var uri = new Uri("http://somedomain.com/path");
    var request = WebRequest.CreateHttp(uri);
    var response = await request.GetResponseAsync();

    ContentDispositionHeaderValue contentDisposition;
    var fileName = ContentDispositionHeaderValue.TryParse(response.Headers["Content-Disposition"], out contentDisposition)
        ? contentDisposition.FileName
        : "noname.dat";
    using (var fs = new FileStream(@"C:\test\" + fileName, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        await response.GetResponseStream().CopyToAsync(fs);
    }

    return true
}

, , , try..catch false , .

+3

Source: https://habr.com/ru/post/1651753/


All Articles