How to check Website/URL exists or not using C#
Sometimes when user enters their website address in user registration form we have to check whether the website or URL entered by the user exists or not.
Below is a simple and very easy code to check website/URL exists or not using C# code.
First we have to add the namespace
using System.Net;
protected void btnURLStatus_Click(object sender, EventArgs e)
{
//bool status = CheckUrlStatus("https://www.google.co.in/");//URL hard coded in the code for testing.
bool status = CheckUrlStatus(txtWebsite.Text);//Here I am taking the value from Textbox where user enters the website address.
if (status == true)
{
lblURLStatus.Text = "Yes the website exists!!!";
}
else
{
lblURLStatus.Text = "Oops the website DOES NOT exists!!!";
}
}
protected bool CheckUrlStatus(string Website)
{
try
{
var request = WebRequest.Create(Website) as HttpWebRequest;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}
I hope this simple code save your time to find whether URL exists or not using ASP.NET