Thursday, August 28, 2008

Check if a URL actually exists


We have seen many validations for URLs.
But what to do if the requirement is like to check whether a URL is in the NET.
In other words, how can one knows the URL given has not returned a 404 error?

Here's the code



/// <summary>
/// Checks the status of the specified URL.
/// </summary>
/// <param name="strURL">The URL that needs to be checked</param>
/// <returns>True if the URL exists</returns>

public bool IsURLValid(string strURL)
{
string strResponse = "";
try
{
string pattern = @"((http|ftp|https):\/\/w{3}[\d]*.|(http|ftp|https):\/\/|w{3}[\d]*.)([\w\d\._\-#\(\)\[\]\\,;:]+@[\w\d\._\-#\(\)\[\]\\,;:])?([a-z0-9]+.)*[a-z\-0-9]+.([a-z]{2,3})?[a-z]{2,6}(:[0-9]+)?(\/[\/a-z0-9\._\-,]+)*[a-z0-9\-_\.\s\%]+(\?[a-z0-9=%&\.\-,#]+)?";
//validatng url in case if it hasn't been validated earlier
if(Regex.IsMatch(strURL,pattern))
{
WebRequest request = HttpWebRequest.Create(strURL);
request.Timeout = 5000;
strResponse = ((HttpWebResponse)request.GetResponse()).StatusCode.ToString();
}
}
catch(Exception exp)
{
strResponse = "";
}
return (strResponse=="OK")? true: false;
}



Does the work, but not very classy.
Any better ideas?

Related Posts :



0 comments on "Check if a URL actually exists"

Add your comment. Please don't spam!
Subscribe in a Reader

Post a Comment