【问题标题】:C# - Get COM Ports with their friendly name using WMIC# - 使用 WMI 获取带有友好名称的 COM 端口
【发布时间】:2019-06-18 01:58:42
【问题描述】:

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

经过一番调查,我发现我可以通过搜索 Name 和 Description 获得使用 WMI/CIMV2/Win32_PnPEntity 的 COM 端口strong> 价值观。

要找到友好名称,我需要在 Win32_PnPSignedDriver 上进行搜索并获取 FriendlyName

的值

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

  • COM56 - 蓝牙设备 - MyBTHDeviceName1
  • COM76 - 蓝牙设备 - MyBTHDeviceName2
  • COM5 - 串行设备 -

我附上我现在获得前两个字段的代码。

// 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;
        }

提前致谢。

【问题讨论】:

  • 考虑 Win32_SerialPort,描述属性。
  • 这很有帮助。我自己发现了 Win32_SerialPort,然后我注意到 Hans Passant 已经暗示过了。我将查询更新为“从 Win32_SerialPort 中选择设备 ID”,在我的系统中,这会产生我需要的 COM3

标签: c# wmi


【解决方案1】:

您正在寻找的“友好名称”仅适用于 COM 端口是虚拟的(我假设它们在您的示例中)。我认为您可以在Win32_PnPEntity 类上查找name 属性所需的信息。无需搜索 COM 端口的其他信息,因为您将获得 Win32_PnPEntity 类的所有信息。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-23
    • 2012-03-11
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 2020-02-18
    相关资源
    最近更新 更多