Network Link Detection in C#

August 3, 2007

This code snippit will show you how to detect if there is a network link on one of the network adaptors on your system. The function is written in C# and uses the Windows Management Instrumentation to get the link status.

/// <summary>
/// Checks if a network is connected to the local machine.
/// </summary>
/// <returns>true if network connected, false if not</returns>
static public boolIsNetworkConnected()
{
    bool connected=false;
    if(SystemInformation.Network)
    {
        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((int)networkAdapter["NetConnectionStatus"]==2)
                {
                    connected = true;
                    break;
                }
            }
        }
        searcher.Dispose();
    }
    return connected;
}

2 Responses to “Network Link Detection in C#”

RSS feed for comments on this post. TrackBack URL

  1. Comment by Glenn Inn — April 2, 2010 at 12:45 am  

    Alex,
    I like your method; there were some improvements that can be done by leveraging the “SQL-like” WMI syntax.

    Here’s the meat of your routine:
    ManagementObjectSearcher searcher=
    new ManagementObjectSearcher(
    “SELECT * FROM Win32_NetworkAdapter where NetConnectionStatus=2″);

    foreach( ManagementObject networkAdapter in searcher.Get())
    {
    connected = true;
    }
    searcher.Dispose();

  2. Comment by Alex LoweJune 10, 2010 at 9:46 pm  

    Thanks for the snippet!

Leave a Reply

*
To prove you're a person (not a spam script), type the answer to the math equation shown in the picture. Click on the picture to hear an audio file of the equation.
Click to hear an audio file of the anti-spam equation