views:

3879

answers:

3

In my application I use the WebClient class to download files from a Webserver by simply calling the DownloadFile method. Now I need to check whether a certain file exists prior to downloading it (or in case I just want to make sure that it exists). I've got two questions with that:

  1. What is the best way to check whether a file exists on a server without transfering to much data across the wire? (It's quite a huge number of files I need to check)
  2. Is there a way to get the size of a given remote file without downloading it?

Thanks in advance!

+12  A: 

WebClient is fairly limited; if you switch to using WebRequest, then you gain the ability to send an HTTP HEAD request. When you issue the request, you should either get an error (if the file is missing), or a WebResponse with a valid ContentLength property.

Edit: Example code:

WebRequest request = WebRequest.Create(new Uri("http://www.example.com/"));
request.Method = "HEAD";

WebResponse response = request.GetResponse();
Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
Tim Robinson
Thanks for your answer! I've seen that I can get a response through the GetResponse() method and then check the ContentLength. But does this make sure the entire file is not downloaded? I can't find a way to send an HTTP HEAD request. Could you point me into the right direction?
Matthias
@Matthias Create a WebRequest with WebRequest.Create(uri) and then set the 'Method' property to "HEAD".
chakrit
What chakrit said; also, see example.
Tim Robinson
Thank you both!
Matthias
A: 

1) System.IO.File.Exists(Server.MapPath("../"));

2)ContentLegth property will help you to find the size of the file.

Kthevar
A: 

Here's a blog post I wrote regarding this matter in the past. I'm putting it here for future searches...

Dor Rotman