如何获取Windows网络适配器使用的连接名称?

时间:2011-12-25 02:52:21

标签: c# .net wmi

是否可以使用WMI查询获取它?

我目前的代码:

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

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

我尝试从以下位置获取连接名称:

Control Panel \ Network and Internet \ Network Connections

1 个答案:

答案 0 :(得分:3)

使用下面的代码,你可以转储网络适配器的所有属性,你需要Name属性:

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

或者只是使用LINQ(添加using System.Linq):

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

PS:还要注意WMI查询中的拼写错误 - 忘记了r中的Adapter:Win32_NetworkAdapte_r _