8

How can I check whether a page exists at a given URL?

I have this code:

private void check(string path)
    {

        try
        {
            Uri uri = new Uri(path);
            WebRequest request = WebRequest.Create(uri);
            request.Timeout = 3000;
            WebResponse response;
            response = request.GetResponse();

        }
        catch(Exception loi) { MessageBox.Show(loi.Message); }

    }

But that gives an error message about the proxy. :(

Max Shawabkeh
  • 37,799
  • 10
  • 82
  • 91
microstar
  • 81
  • 1
  • 1
  • 2

4 Answers4

3

First, you need to understand that your question is at least twofold, you must first check if the server is responsive, using ping for example - that's the first check, while doing this, consider timeout, for which timeout you will consider a page as not existing?

second, try retrieving the page using many methods which are available on google, again, you need to consider the timeout, if the server taking long to replay, the page might still "be there" but the server is just under tons of pressure.

MindFold
  • 771
  • 5
  • 16
2

If the proxy needs to authenticate you with your Windows credentials (e.g. you are in a corporate network) use:

WebRequest request=WebRequest.Create(url);
request.UseDefaultCredentials=true;
request.Proxy.Credentials=request.Credentials;
laktak
  • 57,064
  • 17
  • 134
  • 164
2
try
{
    Uri uri = new Uri(path);
    HttpWebRequest request = HttpWebRequest.Create(uri);
    request.Timeout = 3000;
    HttpWebResponse response;
    response = request.GetResponse();
    if (response.StatusCode.Equals(200))
    {
        // great - something is there
    }
}
catch (Exception loi) 
{ 
    MessageBox.Show(loi.Message); 
}

You can check the content-type and length, see MSDN HTTPWebResponse.

wonea
  • 4,783
  • 17
  • 86
  • 139
mo.
  • 3,474
  • 1
  • 23
  • 20
  • I had better luck formatting my conditional like the following instead of what you have provided, I understand that 200 is the same thing, but I needed to compare it using the StatusCode object for equals to work as expected: response.StatusCode.Equals(response.StatusCode.Equals(HttpStatusCode.OK)) – dkroy Sep 13 '12 at 20:46
0

At a guess, without knowing the specific error message or path, you could try casting the WebRequest to a HttpWebRequest and then setting the WebProxy.

See MSDN: HttpWebRequest - Proxy Property

Daniel Ballinger
  • 13,187
  • 11
  • 69
  • 96