bezzad / Downloader

Fast, cross-platform and reliable multipart downloader with asynchronous progress events for .NET applications.
MIT License
1.25k stars 193 forks source link

README is a bit misleading about Content-Length for getting file length #162

Open MisterMeUA opened 4 months ago

MisterMeUA commented 4 months ago

Content-Length is not used to know a length of file - content-range is (and you properly parse it when making first request with 0,0 range). I got confused because Content-Length must be a length of returned content of request (not a full length of file).

bezzad commented 1 month ago

To determine the length of a file in an HTTP request, you can extract Content-Lenght information from the HTTP headers. The Content-Length header provides the size of the content (file) in bytes. You can send an HTTP HEAD request to retrieve only the header without downloading the entire file. If the server supports it, the Content-Length header will contain the file size. Here’s a method that retrieves the file size from an HTTP URL:

public long GetFileSize(string url)
{
    long result = -1;
    System.Net.WebRequest req = System.Net.WebRequest.Create(url);
    req.Method = "HEAD";
    using (System.Net.WebResponse resp = req.GetResponse())
    {
        if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength))
        {
            result = ContentLength;
        }
    }
    return result;
}

If the server doesn’t allow the HEAD method or the Content-Length header is missing, you may need to download the entire content to determine its size.

Remember that the accuracy of the file size depends on the server’s response. Most servers include the Content-Length header, but it’s essential to handle cases where it’s not available.