How can we check the validity and existence of a URL in C#?


We're developing a application in Visual C# 2022. Our goal is to allow users to input a URL, retrieve the data from that URL, and generate HTML content for them. However, we're encountering a runtime error when users input invalid URLs, as our application attempts to fetch data from non-existent web pages. 

We've been investigating methods to determine whether the provided URL is accessible or not. By "accessible," we mean whether the URL can be reached and data can be retrieved from it, rather than simply checking domain availability.


using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

public class UrlChecker
{
    public async Task<bool> CheckUrl(string url)
    {
        using (var client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(url);
                return response.StatusCode == HttpStatusCode.OK;
            }
            catch (HttpRequestException)
            {
                // URL is not valid or doesn't exist
                return false;
            }
        }
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        string urlToCheck = "https://quickpickdeal.com/api/employee";
        UrlChecker urlChecker = new UrlChecker();
        
        bool isValid = await urlChecker.CheckUrl(urlToCheck);
        
        if (isValid)
        {
            Console.WriteLine("URL is valid and exists.");
        }
        else
        {
            Console.WriteLine("URL is not valid or doesn't exist.");
        }
    }
}
In this code example, we're checking the validity of the URL "https://quickpickdeal.com/api/employee". The UrlChecker class and the Main method remain the same, only the URL being checked is different. 
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

public class UrlChecker
{
    public async Task<bool> CheckUrl(string url)
    {
        using (var client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(url);
                return response.StatusCode == HttpStatusCode.OK;
            }
            catch (HttpRequestException)
            {
                // URL is not valid or doesn't exist
                return false;
            }
        }
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        string urlToCheck = "https://test.com";
        UrlChecker urlChecker = new UrlChecker();
        
        bool isValid = await urlChecker.CheckUrl(urlToCheck);
        
        if (isValid)
        {
            Console.WriteLine("URL is valid and exists.");
        }
        else
        {
            Console.WriteLine("URL is not valid or doesn't exist.");
        }
    }
}


  • The CheckUrl function takes a URL string as input and returns a boolean indicating whether the URL exists and is valid and Inside CheckUrl, an instance of HttpClient is used to send a GET request to the provided URL.If the response status code is HttpStatusCode.OK (200), it means the URL is valid and exists.If any exception occurs during the HTTP request (for example, if the URL is not valid or doesn't exist), it's caught, and the method returns false.