WMI:获取接口名称,状态网络

时间:2018-04-10 01:06:40

标签: c# networking

美好的一天。

(netsh界面show interface)中有4个类别列

  1. 管理状态(已启用)

  2. 状态(已断开连接)或(已连接)

  3. Type(Dedicated)

  4. 接口名称(以太网2)或(Wi-Fi)或(以太网)

  5. 问题1: 如何获取我的接口名称State ="已连接&#34 ;;

    ManagementClass mc = new ManagementClass("Win32_NetworkAdapter");
    foreach (ManagementObject mo in mc.GetInstances())
    {
        int index = Convert.ToInt32(mo["Index"]);
        string name = mo["NetConnectionID"] as string;
        if (!string.IsNullOrEmpty(name))
            MessageBox.Show(name);
            //textBox1.Text += name + Environment.NewLine;
    }
    

    我这里有想成为输出的图像。 Sample Image

    谢谢你们。

1 个答案:

答案 0 :(得分:0)

您可能希望按NetConnectionStatus == 2进行过滤。

<强> NetConnectionStatus

  • 断开连接(0)
  • 连接(1)
  • 已连接(2)
  • 断开连接(3)
  • 硬件不存在(4)
  • 硬件已禁用(5)
  • 硬件故障(6)
  • Media Disconnected(7)
  • 认证(8)
  • 认证成功(9)
  • 身份验证失败(10)
  • 无效地址(11)
  • 证书必填(12)

可用属性及其可能值can be found in the MSDN entry for Win32_NetworkAdapter的列表。

var mc = new ManagementClass("Win32_NetworkAdapter");
mc.GetInstances()
    .OfType<ManagementObject>()
    .Where(mo => !string.IsNullOrEmpty(mo["NetConnectionID"] as string)) // has a ConnectionId
    .ToList()
    .ForEach(mo => Debug.WriteLine($"NetConnectionStatus = {mo["NetConnectionStatus"]} / NetConnectionID={mo["NetConnectionID"]} / Name={mo["Name"]}"));

//Result:
//  NetConnectionStatus=7 / NetConnectionID=Ethernet / Name=Intel(R) Ethernet Connection (5) I219-LM
//  NetConnectionStatus=7 / NetConnectionID=WiFi / Name=Intel(R) Dual Band Wireless-AC 8265
//  NetConnectionStatus=7 / NetConnectionID=Bluetooth Network Connection / Name=Bluetooth Device (Personal Area Network)
//  NetConnectionStatus=2 / NetConnectionID=VMware Network Adapter VMnet1 / Name=VMware Virtual Ethernet Adapter for VMnet1
//  NetConnectionStatus=2 / NetConnectionID=VMware Network Adapter VMnet8 / Name=VMware Virtual Ethernet Adapter for VMnet8