Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find available COM ports?

Tags:

c#

serial-port

How to find available COM ports in my PC? I am using framework v1.1. Is it possible to find all COM ports? If possible, help me solve the problem.

like image 213
RV. Avatar asked Jul 04 '09 09:07

RV.


People also ask

How do you check com1 port is working or not?

To test if the computer COM port is functioning correctly, you can do a simple loopback test. (In a loopback test, a signal is sent from a device and returned, or looped back, to the device.) For this test, connect a serial cable to the COM port that you want to test. Then short pin 2 and pin 3 of the cable together.


2 Answers

Framework v1.1 AFAIK doesn't allow you to do this.

In 2.0 there is a static function

SerialPort.GetPortNames()

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames.aspx

like image 119
Vanuan Avatar answered Sep 27 '22 21:09

Vanuan


As others suggested, you can use WMI. You can find a sample 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);
} 
like image 22
Juanma Avatar answered Sep 27 '22 21:09

Juanma