JL. JL. - 1 year ago 119
C# Question

How can I catch a 404?

I have the following code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Credentials = MyCredentialCache;


How can I catch a specific 404 error? The WebExceptionStatus.ProtocolError can only detect that an error occurred, but not give the exact code of the error.

For example:

catch (WebException ex)
if (ex.Status != WebExceptionStatus.ProtocolError)
throw ex;

Is just not useful enough... the protocol exception could be 401, 503, 403, anything really.

Answer Source

Use the HttpStatusCode Enumeration, specifically HttpStatusCode.NotFound

Something like:

HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {

we is a WebException.

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