size of file located at url

  • Thread starter Thread starter John A Grandy
  • Start date Start date
J

John A Grandy

My web app needs to determine the file size in bytes for image file urls
stored in db. Does .NET provide a method that can determine the file size in
bytes ?
 
John,

Not really. It completely depends on the protocol that the URL
represents. If the protocol is http, or https, then you can do this easily.

You can issue a HEAD request to an HTTP server resource and (assuming it
implements the HTTP 1.1 protocol) it should return a Content-Length header
which you can then use as the size of the file. However, this will only
work for static resources, as dynamically generated pages don't typically
populate this header.

Now, to do this in .NET, you can create a WebRequest/WebResponse for the
particular protocol using the static Create method on the WebRequest class.
Then, you can issue a call to GetResponse, and then access the ContentLength
property on the response that is returned to you.

If you are working with HTTP resources only, then you can do this:

// Create the request.
WebRequest request = WebRequest.Create(url);

// Set the method to HEAD.
request.Method = "HEAD";

// Get the response.
using (WebResponse response = request.GetResponse())
{
// Get the length.
long length = response.ContentLength;
}

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top