Web-based applications involve pages connected by links. Therefore, verifying the authenticity of links becomes a crucial factor. For example, one situation may involve verifyng a link before storing it into a database. Pass to the function a url as a string and it will return true (the link works) or false (the link did not work).

public bool checkUrlLink(string url)
{
HttpWebRequest request = HttpWebRequest)WebRequest.Create(url);
request.Proxy = null;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return true;
}
catch
{
return false;
}
}

This code snippet uses HttpWebRequest and HttpWebResponse functions. Therefore, the snippet above requires the following using statement:

using System.Net;

Also note that this code snippet will also check wheather a url is properly formatted. If the format is not correct, it will return false (simply because the url did not receive a response).

This entry was posted on Tuesday, April 8th, 2008 at 7:56 am and is filed under C#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply