C#枚举所有串口COM

在实际项目中,如需都COM进行操作,往往需要枚举当前电脑中可用的所有串口COM。

我们第一想到的就是SerialPort.GetPortNames()方法。但这种方法有个缺陷那就是不能罗列那些通过USB连接虚拟出来的COM口。


本人在实际工作中的解决方案如下(关键部分)。

//Because Win32_SerialPort can't find the virtual COM ports, use Win32_PnPEntity here
using (var searcher = new ManagementObjectSearcher(@"root\CIMV2""SELECT * FROM Win32_PnPEntity  WHERE Status='OK'"))
{
    foreach (var queryObj in searcher.Get())
    {
        ComPortInfo comPortInfo;
        if (TryParseComPortInfo(queryObj, out comPortInfo))
            _comPortInfoList.Add(comPortInfo);
    }
}

private static bool TryParseComPortInfo(ManagementBaseObject queryObj, out ComPortInfo comPortInfo)
{
    comPortInfo = null;
 
    var captionPropertyValue = queryObj["Caption"as string;
    if (string.IsNullOrWhiteSpace(captionPropertyValue))
        return false;
 
    var portNumber = 0;
    if (!TryParsePortNumber(captionPropertyValue, out portNumber))
        return false;
 
    comPortInfo = new ComPortInfo
    {
        PortName = PortInfoBase.ToPortName(portNumber),
        PortNumber = portNumber,
        Description = queryObj["Description"as string,
        DeviceId = queryObj["DeviceID"as string,
        Manufacturer = queryObj["Manufacturer"as string
    };
 
    return true;
}

如果你在实际项目也遇到类似的问题,希望都你有所帮助。

猜你喜欢

转载自blog.csdn.net/zbbfb2001/article/details/77850069