c# – 如何找到可用的COM端口?

前端之家收集整理的这篇文章主要介绍了c# – 如何找到可用的COM端口?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在PC中找到可用的COM端口?我使用的是框架v1.1.是否可以找到所有COM端口?如有可能,请帮我解决问题.

解决方法

正如其他人建议的,您可以使用WMI.您可以找到一个示例 in CodeProject
try
{
    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher("root\\WMI","SELECT * FROM MSSerial_PortName");

    foreach (ManagementObject queryObj in searcher.Get())
    {
        Console.WriteLine("-----------------------------------");
        Console.WriteLine("MSSerial_PortName instance");
        Console.WriteLine("-----------------------------------");
        Console.WriteLine("InstanceName: {0}",queryObj["InstanceName"]);

        Console.WriteLine("-----------------------------------");
        Console.WriteLine("MSSerial_PortName instance");
        Console.WriteLine("-----------------------------------");
        Console.WriteLine("PortName: {0}",queryObj["PortName"]);

        //If the serial port's instance name contains USB 
        //it must be a USB to serial device
        if (queryObj["InstanceName"].ToString().Contains("USB"))
        {
            Console.WriteLine(queryObj["PortName"] + " 
            is a USB to SERIAL adapter/converter");
        }
    }
}
catch (ManagementException e)
{
    Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
}

猜你在找的C#相关文章