[ACCEPTED]-How to check if a file exists on a server using c# and the WebClient class-exists

Accepted answer
Score: 45

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

Edit: Example 1 code:

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

using(WebResponse response = request.GetResponse()) {
   Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
}
Score: 5

When you request file using the WebClient Class, the 6 404 Error (File Not Found) will lead to 5 an exception. Best way is to handle that 4 exception and use a flag which can be set 3 to see if the file exists or not.

The example 2 code goes as follows:

System.Net.HttpWebRequest request = null;
System.Net.HttpWebResponse response = null;
request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("www.example.com/somepath");
request.Timeout = 30000;
try
{
    response = (System.Net.HttpWebResponse)request.GetResponse();
    flag = 1;
}
catch 
{
    flag = -1;
}

if (flag==1)
{
    Console.WriteLine("File Found!!!");
}
else
{
    Console.WriteLine("File Not Found!!!");
}

You can put your code 1 in respective if blocks. Hope it helps!

Score: 0

What is the best way to check whether a 7 file exists on a server without transfering 6 to much data across the wire?

You can test 5 with WebClient.OpenRead to open the file stream without reading 4 all the file bytes:

using (var client = new WebClient()) 
{
    Stream stream = client.OpenRead(url); 
    // ^ throws System.Net.WebException: 'Could not find file...' if file is not present
    stream.Close(); 
}

This will indicate if 3 the file exists at the remote location or 2 not.

To fully read the file stream, you would 1 do:

using (var client = new WebClient()) 
{
    Stream stream = client.OpenRead(url); 
    StreamReader sr = new StreamReader(stream);
    Console.WriteLine(sr.ReadToEnd());
    stream.Close(); 
}
Score: 0

In case anyone stuck with ssl certificate 1 issue

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback
                                                                            (
                                                                               delegate { return true; }
                                                                            );
            WebRequest request = WebRequest.Create(new Uri("http://.com/flower.zip"));
            request.Method = "HEAD";

            using (WebResponse response = request.GetResponse())
            {
                Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
            }

More Related questions