代码之家  ›  专栏  ›  技术社区  ›  Itay.B

串行端口上的环路

  •  1
  • Itay.B  · 技术社区  · 12 年前

    我正在使用c#FW 4.0。 我想遍历计算机中的所有串行端口,并获取每个端口的全名。 例如,我希望看到“Prolicic USB to Serial Comm Port(COM6)”,而不仅仅是COM6。

    enter image description here

    这是我当前的代码,它只提供COM/1/6等。。。

               string[] ports = SerialPort.GetPortNames();
    
    
            foreach (string port1 in ports)
            {
                MessageBox.Show(port1);
    
            }
    
    1 回复  |  直到 12 年前
        1
  •  3
  •   Community Mohan Dere    9 年前

    你可以利用WMI,看看 WMI Reference

    Juanma回答:, Here .

    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)
    {
        MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
    }