Network Link Detection in C#

July 23, 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.

It is ready to use, as is. It has been used on many projects, personal and professional.

/// <summary>
/// Checks if a network is connected to the local machine.
/// </summary>
/// <returns>true if network connected, false if not</returns>   

static public bool IsNetworkConnected()
{
    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; }

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