使用 ManagementObjectSearcher 查询 Win32_PnPEntity 返回空

Using ManagementObjectSearcher to query Win32_PnPEntity comes back empty

好吧,这让我抓狂。

下面的代码在 Windows 7 和 .NET 3.5 中工作得很好。 在 Windows 8.1 和 .NET 4.5.1 中我得到一个空结果,但是使用 WMI Code Creator 我可以获得结果。

我在网上找不到任何相关信息。

我想获取任何 COM 端口的友好名称,例如"Communications Port (COM1)".

仅使用 System.IO.Ports.SerialPort.GetPortNames() 是不行的。

我真的希望有人知道如何做到这一点。谢谢!

using System;
using System.Collections.Generic;
using System.Management;

namespace OakHub
{
    public class SerialMgmt
    {
        static public List<String> GetCOMDevices()
        {
            List<String> list = new List<String>();

            ManagementScope scope = new ManagementScope(@"\" + Environment.MachineName + @"\root\CIMV2");
            SelectQuery sq = new SelectQuery("SELECT Caption FROM Win32_PnPEntity");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, sq);
            ManagementObjectCollection moc = searcher.Get();

            foreach (ManagementObject mo in moc)
            {
                String name = mo.ToString();
                if (name.ToString().Contains("(COM"))
                {
                    list.Add(name);
                }
            }
            return list;
        }
    }
}

首先我不知道为什么这段代码对你有用(使用 .Net 3.5)。

  1. 您刚刚 select 编辑了 属性 Caption。 (如果需要,使用 * 到 select 全部)
  2. 我想你想要Win32_PnPEntity-Devices的名字,你不能用这行代码得到它

    String name = mo.ToString();

    因为名字是 属性。您首先必须使用 WMI-String 加载 属性 :

    SELECT Name,Caption FROM Win32_PnPEntity //获取名称和标题 属性

    SELECT * FROM Win32_PnPEntity //加载那个WMI-Obj

  3. 的所有属性

然后你必须检查值是否为 null 否则 --> return 值

代码:

public List<String> GetLocalCOMDevices()
        {
            List<String> list = new List<String>();

            ManagementScope scope = new ManagementScope(@"\" + Environment.MachineName + @"\root\CIMV2");
            SelectQuery sq = new SelectQuery("SELECT Name,Caption FROM Win32_PnPEntity");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, sq);
            ManagementObjectCollection moc = searcher.Get();

            foreach (ManagementObject mo in moc)
            {
                object propName = mo.Properties["Name"].Value;
                if (propName == null) { continue; }

                list.Add(propName.ToString());
            }
            return list;
        }