1

I want to validate an url, whether it exists or throwing page not found error. can anyone help me how to do it in asp.net. for e.g., my url may be like http://www.stackoverflow.com or www.google.com i.e., it may contain http:// or may not. when i check, it should return the webpage valid if exists or page not found if doesnot exists

i tried HttpWebRequest method but it needs "http://" in the url.

thanks in advance.

2 Answers 2

4
protected bool CheckUrlExists(string url)
    {
        // If the url does not contain Http. Add it.
        if (!url.Contains("http://"))
        {
            url = "http://" + url;
        }
        try
        {
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "HEAD";
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                return response.StatusCode == HttpStatusCode.OK;
            }
        }
        catch 
        {
            return false;
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for ur reply.. u idea is good, but some sites will be secured where it should have "https://". so how can we differenciate that type with normal websites..
2

Try this

using System.Net;
////// Checks the file exists or not.

bool FileExists(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 it Exist
       return (response.StatusCode == HttpStatusCode.OK);
    }
  catch
   {
        //Any exception will returns false. So the URL is Not Exist
        return false;
   }
}

Hope I Helped

1 Comment

hi.. thanks for ur reply.. i checked it, when i passed a url without "http://" like "www.google.com" its throws this error "Invalid URI: The format of the URI could not be determined." i want to handle this type of problems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.