mrblah mrblah - 1 year ago 93
C# Question

can I check if a file exists at a URL?

I know I can locally, on my filesystem, check if a file exists:


Can I check at a particular remote URL?

Answer Source

If you're attempting to verify the existence of a web resource, I would recommend using the HttpWebRequest class. This will allow you to send a HEAD request to the URL in question. Only the response headers will be returned, even if the resource exists.

var url = "";
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";

    response = (HttpWebResponse)request.GetResponse();
catch (WebException ex)
    /* A WebException will be thrown if the status of the response is not `200 OK` */
    // Don't forget to close your response.
    if (response != null)

Of course, if you want to download the resource if it exists it would most likely be more efficient to send a GET request instead (by not setting the Method property to "HEAD", or by using the WebClient class).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download