C#: How to validate URL in c#.

Some time we come in situation to validate entered URL before retrive data from that URL. Below is some piece of code which will do validation by trying to download some content form URL.

First Method:

using System.Net;

private bool ValidateUrl(string url)
{
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //Returns TURE if the Status code == 200
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        //Any exception will returns false.
        return false;
    }
}

Second Method:


        public bool IsValidUrl(string url)
        {
            string testData = string.Empty;
            try
            {
                System.Text.Encoding enc = System.Text.Encoding.ASCII;
                WebClient obj = new WebClient();
                testData = enc.GetString(obj.DownloadData(url));              
            }
            catch (Exception ee)
            {
                //Any exception will returns false.
                return false;
            }
            return testData.Length != 0 ? true:false;
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s