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; }
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();
Thanks for the snippet!