Check if HTTP connection to website is available

Check if HTTP connection to website is available
Sample code that uses a ConnectionAvailable() method to check whether the connection to an HTTP server went through or not. Can be used to check if a certain website is online as well as if Internet connection is available on the target machine.
1. using System;
2. using System.Collections.Generic;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Text;
7. using System.Windows.Forms;
8. using System.Net;
9. 
10. namespace Labs
11. {
12.     public partial class Form1 : Form
13.     {
14.         public Form1()
15.         {
16.             InitializeComponent();
17.         }
18.  
19.         private void Form1_Load(object sender, EventArgs e)
20.         {
21.             // Returns True if connection to http://www.google.com was successful
22.             MessageBox.Show(ConnectionAvailable("http://www.google.com").ToString());
23.         }
24. 
25.         public bool ConnectionAvailable(string strServer)
26.         {
27.             try
28.             {
29.                 HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create(strServer);
30. 
31.                 HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
32.                 if (HttpStatusCode.OK == rspFP.StatusCode)
33.                 {
34.                     // HTTP = 200 - Internet connection available, server online
35.                     rspFP.Close();
36.                     return true;
37.                 }
38.                 else
39.                 {
40.                     // Other status - Server or connection not available
41.                     rspFP.Close();
42.                     return false;
43.                 }
44.             }
45.             catch (WebException)
46.             {
47.                 // Exception - connection not available
48.                 return false;
49.             }
50.         }
51.     }
52. }

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top