How to check to make sure a URL is valid

Referred URL - http://www.developerfusion.com/code/4267/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 May Also Like

0 comments