0

I'm using the following method to check if a URL Exists or is valid.

class MyClient : WebClient
{
    public bool HeadOnly { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest req = base.GetWebRequest(address);

        if (HeadOnly && req.Method == "GET")
        {
            req.Method = "HEAD";
        }
        return req;
    }
}

private static Boolean CheckURL(string url)
{
    using (MyClient myclient = new MyClient())
    {
        try
        {
            myclient.HeadOnly = true;
            // fine, no content downloaded
            string s1 = myclient.DownloadString(url);
            return true;
        }
        catch (Exception error)
        {
            return false;
        }
    }
}

Is my approach correct? How to Display the Status of a checked URL eg:404,Success etc to the user?

Please advice..

4
  • 3
    You need to look at the status code exposed by a WebException: Possible duplicate of Web Response status code Commented Jul 10, 2017 at 11:32
  • You should probably also include a believable user-agent header. Commented Jul 10, 2017 at 11:33
  • @AlexK. Do you mind adding it as an answer.. Commented Jul 10, 2017 at 11:41
  • You can close this question as a duplicate yourself. Commented Jul 10, 2017 at 11:47

1 Answer 1

2

Here is your question of answer.

public static void isURLExist(string url)
    {
        try
        {
            WebRequest req = WebRequest.Create(url);

            WebResponse res = req.GetResponse();

            Console.WriteLine("Url Exists");
        }
        catch (WebException ex)
        {
            Console.WriteLine(ex.Message);
            if (ex.Message.Contains("remote name could not be resolved"))
            {
                Console.WriteLine("Url is Invalid");
            }
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

specific message it's depend on your requirement.
WebResponse implements IDisposable - you should be sure to dispose of it

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.