Posts Tagged ‘httpwebresponse’

Check If A Url Works in C#

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).