Ali Tor
Ali Tor

Reputation: 2995

WebRequest.AddRange doesn't return the correct Content-Length

I want to download a file in a url partially. But it returns the wrong content size and i couldn't figure out why. The remote file has Accept-Ranges=bytes How can it be solved?

long start = 536871935, end = 805306878;
string url = "http://ipv4.download.thinkbroadband.com/1GB.zip";

var request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362";
request.AllowAutoRedirect = true;
request.Method = "GET";
request.Timeout = 5000;
request.ReadWriteTimeout = 3000;
request.AddRange(start, end);

var response = (HttpWebResponse)request.GetResponse();
if (response.ContentLength != end - start + 1)
    throw new Exception(string.Format("Returned content size is wrong; start={0}, end={1}, returned = {2}, shouldbe = {3}",
            start, end, response.ContentLength, end - start + 1));
        

An exception of type 'System.Exception' occurred in Downloadmanager.exe but was not handled in user code

Additional information: Returned content size is wrong start=536871935, end=805306878, returned = 536869889, shouldbe = 268434944

Upvotes: 1

Views: 172

Answers (1)

aepot
aepot

Reputation: 4824

I'm using HttpClient instead of HttpWebRequest (as recommended by Microsoft) and have no such problem.

public class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        long start = 536871935, end = 805306878;
        try
        {
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://ipv4.download.thinkbroadband.com/1GB.zip"))
            {
                request.Headers.Range = new RangeHeaderValue(start, end);
                using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();
                    Console.WriteLine(response.Content.Headers.ContentLength);
                    Console.WriteLine(end - start + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }
}

Console output

268434944
268434944

Upvotes: 1

Related Questions