Saturday, March 31, 2012

How to check if Internet Connection Available through Dot Net Code

Checking whether an Internet connection is available isn’t always as easy as it sounds.
Admittedly, there is a Windows API call that can check whether a connection exists, but it’s extremely fragile and returns incorrect results if the machine has never had Internet Explorer configured correctly. Oops.

The best method is to actually make a Web request and see whether it works. If it does, you’ve got your connection. The following neat code snippet does exactly that. Just call IsConnectionAvailable and check the return value:

Public Function IsConnectionAvailable() As Boolean
' Returns True if connection is available
' Replace www.yoursite.com with a site that
' is guaranteed to be online - perhaps your
' corporate site, or microsoft.com
Dim objUrl As New System.Uri("http://www.yoursite.com/")
' Setup WebRequest
Dim objWebReq As System.Net.WebRequest
objWebReq = System.Net.WebRequest.Create(objUrl)
Dim objResp As System.Net.WebResponse
Try
' Attempt to get response and return True
objResp = objWebReq.GetResponse
objResp.Close()
objWebReq = Nothing
Return True
Catch ex As Exception
' Error, exit and return False
objResp.Close()
objWebReq = Nothing
Return False
End Try

Here’s how you might use this function in your application:

If IsConnectionAvailable() = True Then
MessageBox.Show("You are online!")
End If