views:

251

answers:

2

I want to check the status of a page (404, moved, etc). How can i do it? ATM i am doing the below which only tells me if the page exist or not. Also, i suspect the exception is making my code slow (i tested it)

static public bool CheckExist(string url)
        {
            HttpWebRequest wreq = null;
            HttpWebResponse wresp = null;
            bool ret = false;

            try
            {
                wreq = (HttpWebRequest)WebRequest.Create(url);
                wreq.KeepAlive = true;
                //wreq.Method = "HEAD";
                wresp = (HttpWebResponse)wreq.GetResponse();
                ret = true;
            }
            catch (System.Net.WebException)
            {
            }
            finally
            {
                if (wresp != null)
                    wresp.Close();
            }
            return ret;
        }
+1  A: 

The HttpWebResponse class exposes a StatusCode property which returns a value from the HttpStatusCode enum. In the non-error case, this directly gives you the status code (404 not found, 403 unauthorised, 301 moved permanently, 200 OK and so on). In the error case, the WebException class exposes a Status property - taken from a different enum, but you'll be able to identify the cases you want from that I'd have thought.

David M
I think your saying theres no way to get the page status w/o having an exception when its 404/403/etc. I'll keep this in mind.
acidzombie24
Yes, the behaviour for one of these "erroring" HTTP statuses is to throw a WebException.
David M
+1  A: 

You can get the http error code like this:

catch (System.Net.WebException e)
{
    int HttpStatusCode = (int)((HttpWebResponse)e.Response).StatusCode;
}
Nathan Reed