C# - 使用 WMI 获取带有友好名称的 COM 端口

C# - Get COM Ports with their friendly name using WMI

我正在开发 C# 解决方案,我想获取 COM 端口、描述和友好名称(如果它们是蓝牙)。

经过一番调查,我发现我可以通过搜索 Name 使用 WMI/CIMV2/Win32_PnPEntity 获取 COM 端口] 和 描述 值。

要找到友好名称,我需要在 Win32_PnPSignedDriver 上搜索并获取 FriendlyName[=11= 的值]

有没有办法匹配它们以获得这样的列表?

我附上我现在拥有的代码以获取前两个字段。

// Method to retrieve the list of all COM ports.
        public static List<PortInfo> FindComPorts()
        {
            List<PortInfo> portList = new List<PortInfo>();
            ConnectionOptions options = PrepareOptions();
            ManagementScope scope = PrepareScope(Environment.MachineName, options, @"\root\CIMV2");

            // Prepare the query and searcher objects.
            ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
            ManagementObjectSearcher portSearcher = new ManagementObjectSearcher(scope, objectQuery);

            using (portSearcher)
            {
                string caption = null;
                // Invoke the searcher and search through each management object for a COM port.
                foreach (ManagementObject currentObject in portSearcher.Get())
                {
                    if (currentObject != null)
                    {
                        object currentObjectCaption = currentObject["Caption"];
                        if (currentObjectCaption != null)
                        {
                            caption = currentObjectCaption.ToString();
                            if (caption.Contains("(COM"))
                            {
                                PortInfo portInfo = new PortInfo();
                                portInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
                                portInfo.Description = caption;
                                portList.Add(portInfo);
                            }
                        }
                    }
                }
            }
            return portList;
        }

提前致谢。

您正在寻找的 "friendly name" 仅适用于 COM 端口是虚拟的(我假设它们在您的示例中)。我认为您只需在 Win32_PnPEntity class 上查找 name 属性 即可获得所需的信息。无需搜索有关 COM 端口的其他信息,因为您将获得有关 Win32_PnPEntity class.

的所有信息

您也可以尝试使用 ORMi 并为此使用强类型对象。