Network Link Detection in C#

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;
}


No comments yet. Be the first.

Leave a reply