Thomas Müller
Thomas Müller

Reputation: 21

Check if a website is alive with c#?

i'm new to c# and i'd like to create a tool in visual studio that can check if a website is alive or not. I found out that i have to do a head request and check if i get a 200 respond. I searched in google and here but i can't find a proper solution. The things i tried out didn't work. Any help would be much appreciated. thx?

Upvotes: 2

Views: 2366

Answers (3)

Ben M
Ben M

Reputation: 22492

bool IsWebsiteUp(Uri uri)
{
    try
    {
        var request = System.Net.WebRequest.Create(uri);
        request.Method = "HEAD";
        var response = (HttpWebResponse)request.GetResponse();
        return response.StatusCode == HttpStatusCode.OK;
    }
    catch
    {
        return false;
    }
}

Upvotes: 0

Osama Javed
Osama Javed

Reputation: 1442

if you want to just check if the webserver is responding have a look at this link which shows how to ping another machine otherwise use this link for information about retrieving webpages

Upvotes: 1

James Hill
James Hill

Reputation: 61792

Try this:

WebRequest request = WebRequest.Create("Site goes here");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response == null || response.StatusCode != HttpStatusCode.OK)
{
    //Site is down
}
else
{
    //Site is up
}

Upvotes: 4

Related Questions