how can I use C# HttpClient to download a part of large file

1.4k views Asked by At

How can I use C# HttpClient to download a part of large file, like HttpWebRequest.AddRange(123)?

public async void StartDownload(CancellationToken cancellationToken)
{
    try
    {
        if (_isWork)
            return;

        _isWork = true;
        using (var response = await GetAsync(_doenloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
            await DownloadFileFromHttpResponseMessage(response);
    }
    catch (Exception e)
    {
        downloadExceptiondHandler?.Invoke(_doenloadUrl, e);
    }
}
1

There are 1 answers

0
Paul Kertscher On

There is a Range header specified in the HTTP protocol for that very purpose:

The Range HTTP request header indicates the part of a document that the server should return. [...] The server can also ignore the Range header and return the whole document with a 200 status code. (source, emphasis mine)

Therefor you cannot rely on the server returning only that range of the file.

However, in a HttpRequest there is a property Range in HttpRequestHeaders to set the Range of a request

private async Task<HttpResponseMessage> GetAsync(string downloadUrl, 
                                                 int rangeStart, 
                                                 int rangeEnd)
{
    // Beware: C# 8, use a using block with older language specifications
    using var request = new HttpRequestMessage 
                            { 
                                RequestUri = new Uri(donloadUrl), 
                                Method = HttpMethod.Get 
                            };

    request.Headers.Range = new RangeHeaderValue(rangeStart, rangeEnd);
    return await _httpClient.SendRequestAsync(request);
}