so I've figured on how to get remote files their file size from over the internet with the following code:
WebRequest req = WebRequest.Create(url);
req.Method = "HEAD";
using (WebResponse resp = req.GetResponse())
{
int ContentLength;
if (int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
{
// Stuff ~
}
}
How do I get a remote file its size without the Content-Length option?
I'm really out of ideas and I've searched the internet for several hours, being unable to find it. If anyone knows, would you please be so kind to help me?
Sapphire ~
EDIT
For example, this file doesn't seem to have a content-length? http://ag.teamdna.de/files/advancedgenetics-1.4.3-1.6.jar
Solution
I used GET instead of HEAD which seems to work without any problem whatsoever :)!
According to the standard:
The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request.
Unfortunately there are many HTTP servers out there that don't function accurately with regards to the Content-Length
header. Since the HEAD
response has no actual content they return a different Content-Length
than a GET
would do.
Fortunately we can get the true headers by issuing a GET
request then disposing of the response without reading the content. The response comes back as soon as the headers have been received and before all of the file has been downloaded. If you never read the content it doesn't get fully downloaded. When you dispose of the response object it closes the connection to the server, terminating the transfer.
Try your code as a GET
instead of a HEAD
.