Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
MisterMeUA opened this issue Feb 8, 2024 · 1 comment

Comments

@MisterMeUA
Copy link

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
Copy link
Owner

bezzad commented May 27, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants