1

How do I check if a page exists without wrapping it in a try catch

Dim myWebResponse As HttpWebResponse = CType(myWebRequest.GetResponse(), HttpWebResponse)

If the page does not exist then I get a 404 exeption when myWebRequest.GetResponse() fires.

Isnt there some thing like myWebRequest.DoesPageExist() that returns true of false or the status?

Hello-World
  • 9,277
  • 23
  • 88
  • 154
  • 1
    You could try it with an Ajax call... http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript – WraithNath Jul 23 '12 at 10:35
  • May I ask what you're trying to achieve? I mean, why would you call a URL that might not exist? As I see it, if you're calling that url, you should be expecting it to exist, so it will indeed be an exceptional event if it's not there. Representing this as an Exception makes sense, doesn't it? – Gaute Løken Jul 23 '12 at 10:35

2 Answers2

3

This is not possible.

To check if a page exists, you have to execute the web request, and the server will return an error code, if the page does not exist. If the page exists, the server returns the page content. All this is one in a single server request, if you would check first, you would need two server requests, which is unefficient.

When you execute a web request, you should always catch exceptions, because lots of unexpected things could happen. Not only that the page does not exists, the connection could timeout or break, the server itself is down.... and you should catch all these exceptions.

Carsten Schütte
  • 4,408
  • 1
  • 20
  • 24
1

Have you tried doing it with ajax? (this example uses jQuery)

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

Here is the code for checking 404 status, whitout using jquery

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

taken from:

How do I check if file exists in jQuery or JavaScript?

Community
  • 1
  • 1
WraithNath
  • 17,658
  • 10
  • 55
  • 82