0
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/afakepage");
request.Method = WebRequestMethods.Http.Head;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
bool pageExists = response.StatusCode == HttpStatusCode.OK;

When the address is an invalid one the software crashes on the 3rd line of the code when its supposed to get response, any way to work around this?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
First Second
  • 117
  • 2
  • 2
  • 10

1 Answers1

1

You can get the response like this

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/afakepage");
    request.Method = WebRequestMethods.Http.Head;
    try
    {
        using (WebResponse response = request.GetResponse())
        {

        }
    }
    catch (WebException e)
    {
        using (WebResponse response = e.Response)
        {
            HttpWebResponse httpResponse = (HttpWebResponse) response;
            MessageBox.Show(httpRespnse.StatusCode.ToString());
        }
    }
Ehsan
  • 31,833
  • 6
  • 56
  • 65