Search code examples
c#.netwmi

How to get connection name used by the Windows Network adapter?


Is it possible get it using WMI query?

my current code:

ManagementObjectSearcher searcher = new ManagementObjectSearcher(
                                       "SELECT * FROM Win32_NetworkAdapte");

foreach (ManagementObject queryObj in searcher.Get())
{
     Console.WriteLine(queryObj[??]);        
}

I'm tried get the connections name from:

Control Panel \ Network and Internet \ Network Connections

Solution

  • Using code below you would be able dump all properties of the Network Adapter, you need Name property:

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(
        "SELECT * FROM Win32_NetworkAdapter");
    
    foreach (ManagementObject adapter in searcher.Get())
    {
        StringBuilder propertiesDump = new StringBuilder();
        foreach (var property in adapter.Properties)
        {
            propertiesDump.AppendFormat(
                "{0} == {1}{2}", 
                property.Name, 
                property.Value, 
                Environment.NewLine);        
        }
    }
    

    OR simply using LINQ (add using System.Linq):

    foreach (ManagementObject adapter in searcher.Get())
    {
       string adapterName = adapter.Properties
                                   .Cast<PropertyData>()
                                   .Single(p => p.Name == "Name")
                                   .Value.ToString();
    }
    

    PS: Also be aware you've typo in WMI query - forgot r in Adapter: Win32_NetworkAdapte_r_