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

本文关键字:连接 何获得 Windows 网络适配器 | 更新日期: 2023-09-27 18:18:41

是否可以使用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

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

使用下面的代码,您将能够转储网络适配器的所有属性,您需要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 (add using System.Linq):

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

PS:也要注意你在WMI查询中输入错误-忘记rAdapter: Win32_NetworkAdapte_r_

让我们稍微修改一下代码并缩短它。ManagementClass class缩短了WMI查询。

ManagementClass mc = new ManagementClass("Win32_NetworkAdapter");
ManagementObjectCollection results = mc.GetInstances();
foreach (var result in results)
{
    foreach (PropertyData data in result.Properties)
        Console.WriteLine($"{data.Name} == {data.Value}");
}