Check URL validity ASP.net

By Chris Gaskell

A handy little function I’ve been using for a while to check if a URL is valid.

The code actually opens the URL and returns the content (html in most cases) as a string. If the code fails it will fall in the catch block, meaning the URL isn’t valid.

I dont like using a try catch like this as it creates a relatively large overhead – especially if it’s used multiple times in a single postback etc. I’ve tried some different methods and had a poke on the web but didn’t manage to get rid of the try statement. If you have any further ideas please comment.

 Dont forget if the file is within filesystem reach (on the same computer or within network range) then you could use System.IO to check the file exists.

Public Class UrlValidity

Public Shared Function IsValid(ByVal Url As String) As Boolean
Dim sStream As Stream
Dim URLReq As HttpWebRequest
Dim URLRes As HttpWebResponse

Try
     URLReq = WebRequest.Create(Url)
     URLRes = URLReq.GetResponse()
     sStream = URLRes.GetResponseStream()
     Dim reader As String = New StreamReader(sStream).ReadToEnd()
     Return True
Catch ex As Exception
     ‘Url not valid
     Return False
End Try
End Function

End Class

6 Responses to “Check URL validity ASP.net”

  1. Phil Winstanley Says:

    I’d do it a little differently: -

    1. Check the URL using a regular expression.
    2. Remove the Try/Catch
    3. Check the .Status property of the Response

    If the Status property is 200 or 302 (Object moved), then the URL is valid, if it’s any other status code it’s invalid.

  2. Terry Cornwell Says:

    I’ve been playing with this for a while now and can’t see a way to make it work without the Try Catch block… When I try non existent domains the GetResponse() method throws the “The remote name could not be resolved: ‘domainname.com’” exception.

    Phil?

  3. jbmixed Says:

    yes, because a readtoend can be deadly dangerous (if the file to check is a large .exe for example)

  4. Stewart Says:

    Jb you are right

  5. Jim Says:

    just remove the try/catch

  6. dotnetguts Says:

    Good Information :)

    Thanks,
    Dotnetguts
    http://dotnetguts.blogspot.com

Leave a Reply