Thursday, 20 December 2012

Validating URL Programatically Using Regex


Validating URL Programatically Using Regex


Using this Code One could check whether the URL is in existence ie., being currently hosted by any server..


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;

}

No comments:

Post a comment

Thank You for Your Comments. We will get back to you soon.

back to top