max
max

Reputation: 3

Checking if URL is Valid -404/Not Found

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..

Upvotes: 0

Views: 3451

Answers (1)

Pratius Dubey
Pratius Dubey

Reputation: 673

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");
            }
        }
    }

Upvotes: 2

Related Questions