【发布时间】: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