Test if a website is alive from a C# application

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response == null || response.StatusCode != HttpStatusCode.OK)

As @Yanga mentioned, HttpClient is probably the more common way to do this now.

HttpClient client = new HttpClient();
var checkingResponse = await client.GetAsync(url);
if (!checkingResponse.IsSuccessStatusCode)
{
   return false;
}

While using WebResponse please make sure that you close the response stream ie (.close) else it would hang the machine after certain repeated execution. Eg

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sURL);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
// your code here
response.Close();

from the NDiagnostics project on CodePlex...

public override bool WebSiteIsAvailable(string Url)
{
  string Message = string.Empty;
  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);

  // Set the credentials to the current user account
  request.Credentials = System.Net.CredentialCache.DefaultCredentials;
  request.Method = "GET";

  try
  {
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
      // Do nothing; we're only testing to see if we can get the response
    }
  }
  catch (WebException ex)
  {
    Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
  }

  return (Message.Length == 0);
}

Tags:

C#

Webrequest