I would like to know how to check if a website is offline or online using C#?
-
2Please ask your 2nd question as a separate post. This isn't a forum. – Soviut Oct 15 '09 at 06:44
-
1Here is a simialr questions about [Best way to test if a website is alive from a C# applicaito](http://stackoverflow.com/questions/186894/best-way-to-test-if-a-website-is-alive-from-a-c-applicaiton)n – Shoban Oct 15 '09 at 07:04
5 Answers
Try to hit the URL using HttpWebClient over an HTTP-GET Request. Call GetResponse() method for the HttpWebClient which you just created. Check for the HTTP-Status codes in the Response.
Here you will find the list of all HTTP status codes. If your request status code is statrting from 5 [5xx] which means the site is offline. There are other codes that can also tell you if the site is offline or unavailable.You can compare the codes against your preferred ones from the entire List.
//Code Example
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://www.stackoverflow.com");
httpReq.AllowAutoRedirect = false;
HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse();
if (httpRes.StatusCode==HttpStatusCode.NotFound)
{
// Code for NotFound resources goes here.
}
// Close the response.
httpRes.Close();

- 42,787
- 22
- 113
- 137
-
-
wont this produce an error if the page/url isnt found? I get exceptions – BerggreenDK Apr 12 '11 at 13:57
First off, define "online" and "offline". However, if your codebehind code is running, your site is online.

- 113,561
- 39
- 200
- 288
-
no i like to to check for a specific url and then I thought I get a true or false or a status returned, but I dont know how to do it. – Marc Oct 15 '09 at 06:48
-
@snarebold: I would agree with Anton; if you codebehind is running, your site is online. Is it that by "Online" you mean, you want to check from your asp.net project if the system is connected to internet? – KMån Oct 15 '09 at 06:59
For my web apps, I use a setting called Offline, which admin can set on/off. Then I can check that setting programmatically. I use this Offline setting, to show friendly maintenance message to my users. Additionally you can use App_Offline.htm, reference : http://www.15seconds.com/issue/061207.htm
http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx

- 3,954
- 7
- 30
- 36
-
thank you. my question was not really correct. may be i like to set in a var in code behind "www.google.com" and it tells me if its offline or not. I just searched arount. I think I have to do any complicated steps with httpwebrequest:S – Marc Oct 15 '09 at 06:59
If you mean online/offline state that controls IIS, then you can control this, with custom Web Events (Application Lifetime Events)

- 7,840
- 8
- 51
- 60