Keeper
Keeper

Reputation: 31

How do I determine if internet file exists on server?

Until recently I have used HttpWebRequest to determine if a file exists on the internet. But now, I realize that a server could handle the 404 if it did not exist and I would only get the default 404 server error page. In this scenario, the HttpWebRequest would not throw an exception. I can't think of a way to tell if there was a 404 error that occurred.

Any ideas?

Upvotes: 0

Views: 233

Answers (3)

Gerard Sexton
Gerard Sexton

Reputation: 3200

On a server that returns a 'page not found' page, if you try to get a nonexistant file in your browser and look in the dev tools, the return code is still 404 Not Found.

Normally, you would expect the HttpWebRequest.GetResponse method to return an http response code but instead .NET throws an exception for http errors.

try {  
    HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
    using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse())
    {            
        if (httpRes.StatusCode == HttpStatusCode.OK)
            Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}", httpRes.StatusDescription);
        // Releases the resources of the response.
        httpRes.Close();
    }
}
catch (WebException ex) {
    Console.WriteLine("Error returned: {0}",ex.Response);
    // can throw again here.
    throw;
}

Upvotes: 0

spender
spender

Reputation: 120450

If GetResponse or its async equivalent is throwing, catch the WebException and you'll find it has a number of handy properties.

In particular, WebException.Response could be very useful to you.

Upvotes: 0

HABO
HABO

Reputation: 15816

Check the StatusCode and StatusResponse in the HttpWebResponse. You can always throw based on the value received.

Upvotes: 2

Related Questions