1

I just got myself into using the SerialPort object in C# and I realised it throws an exception saying that "COM1" does not exist. I checked my device manager to see what COM ports I can use, but is there a way to find out what COM ports are available and programmatically select one of them?

3 Answers 3

5

Yes, use SerialPort.GetPortNames(), which returns an array of strings of available port names.

Then create your SerialPort object by specifying one of the names in the constructor.

string[] ports = SerialPort.GetPortNames();
SerialPort port = new SerialPort(ports[0]);  // create using first existing serial port, for example
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, it worked. In my problem I created a method called USBValidator, it has a 'for' loop with i starting at 0 and ending at SerialPort.GetPortNames().Length. Inside that loop I put USB.PortName = SerialPort.GetPortNames()[i], which automatically made my serial port be assigned to the right COM port.
2

Here is another way

bool portExists = SerialPort.GetPortNames().Any(x => x == "COM1");

1 Comment

I prefer this inline solution.
1

One-liner :

if(SerialPort.GetPortNames().ToList().Contains(comportName)) 
{
    port = new SerialPort(comportName)
}

1 Comment

this is way better than any other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.