Open MisterMeUA opened 4 months 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.
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).