How to check to make sure a URL is valid

If you have users enter URLs and you would like to check them to make sure they exist before you save them to the database, here is the code:

public static bool UrlIsValid(string smtpHost)
{
    bool br = false;
    try {
        IPHostEntry ipHost = Dns.Resolve(smtpHost);
        br = true;
    }
    catch (SocketException se) {
        br = false;
    }
    return br;
}

To use, simply call UrlIsValid with the host name, for example:

string url = "www.google.com";
if(UrlIsValid(url)) {
    Response.Write("The URL '" + url + "' is valid.");
} else {
    Response.Write("The URL '" + url + "' is NOT valid.");
}

You might also like...

Comments

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Never trust a programmer in a suit.” - Anonymous