How To Determine Network Connectivity

The MSDN help states that the SystemInformation.Network method in the .NET framework will return back if the machine has a network connection (not necessarily a connection to the Internet). I have tested this method with my cable in and out and it always returns True. So I searched for the “right” way to determine this. I fixed up the code below that I found on the web. It’s pretty simple and uses WMI. (If you have not used WMI to get system information, you should really check it out.) Simply add a reference to System.Management to your application and drop in the code below.

C#

private bool IsNetworkConnected()
{
  bool connected = SystemInformation.Network;
  if (connected)
  { 
    connected = false;
    System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(“SELECT NetConnectionStatus FROM Win32_NetworkAdapter”);
    foreach (System.Management.ManagementObject networkAdapter in searcher.Get())
    {
      if (networkAdapter[“NetConnectionStatus”] != null)
      {
        if (Convert.ToInt32(networkAdapter[“NetConnectionStatus”]).Equals(2))
        {
          connected = true;
          break;
        }
      }
    }
    searcher.Dispose();
  }
  return connected;
}

VB

Private Function IsNetworkConnected() As Boolean
  Dim connected As Boolean = SystemInformation.Network()
  If connected Then
    connected = False
    Dim searcher As New Management.ManagementObjectSearcher(“SELECT NetConnectionStatus FROM Win32_NetworkAdapter”)
    For Each networkAdapter As Management.ManagementObject In searcher.Get()
      If (Not IsNothing(networkAdapter(“NetConnectionStatus”))) Then
        If Convert.ToInt32(networkAdapter(“NetConnectionStatus”)).Equals(2) Then
          connected = True
          Exit For
        End If
      End If
    Next
    searcher.Dispose()
  End If
  Return connected
End Function

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s