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

3
我需要使用C#查询网络适配器的硬件ID。使用System.Management,我可以查询设备ID、描述等详细信息,但无法查询硬件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相关联。任何帮助将不胜感激。

不,我需要网络适配器的硬件ID。并且不需要有关处理器的任何详细信息。 - this-Me
1个回答

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

1
Simon,我收到了无效查询异常。 - this-Me
1
我的环境:XP嵌入式SP-2。 - this-Me

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接