如何在C#中以编程方式获取网络适配器的硬件ID

时间:2011-09-20 05:31:28

标签: c# wmi-query

我需要使用C#查询网络适配器的Hardware-Id。

使用System.Management我可以查询deviceID,描述等的详细信息,但不能查询硬件ID。

其中,listBox1是一个简单的列表框控件实例,用于显示winform应用程序中的项目。

例如:

ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select * From Win32_NetworkAdapter");
                mbsList = mbs.Get();
                foreach (ManagementObject mo in mbsList)
                {
                    listBox1.Items.Add("Name : " + mo["Name"].ToString());
                    listBox1.Items.Add("DeviceID : " + mo["DeviceID"].ToString());
                    listBox1.Items.Add("Description : " + mo["Description"].ToString());
                }

然而,查看MSDN WMI参考,我无法获得HardwareId。 通过使用devcon工具( devcon hwids = net )但我知道每个设备都与HardwareId相关联

非常感谢任何帮助

1 个答案:

答案 0 :(得分:3)

您正在寻找的HardwareID位于另一个WMI类中。获得Win32_NetworkAdapeter的实例后,可以使用PNPDeviceId选择Win32_PnpEntry。下面是一个示例代码,列出了所有网络适配器及其硬件ID(如果有):

        ManagementObjectSearcher adapterSearch = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapter");

        foreach (ManagementObject networkAdapter in adapterSearch.Get())
        {
            string pnpDeviceId = (string)networkAdapter["PNPDeviceID"];
            Console.WriteLine("Description  : {0}", networkAdapter["Description"]);
            Console.WriteLine(" PNPDeviceID : {0}", pnpDeviceId);

            if (string.IsNullOrEmpty(pnpDeviceId))
                continue;

            // make sure you escape the device string
            string txt = "SELECT * FROM win32_PNPEntity where DeviceID='" + pnpDeviceId.Replace("\\", "\\\\") + "'";
            ManagementObjectSearcher deviceSearch = new ManagementObjectSearcher("root\\CIMV2", txt);
            foreach (ManagementObject device in deviceSearch.Get())
            {
                string[] hardwareIds = (string[])device["HardWareID"];
                if ((hardwareIds != null) && (hardwareIds.Length > 0))
                {
                    Console.WriteLine(" HardWareID: {0}", hardwareIds[0]);
                }
            }
        }