92AlanC
92AlanC

Reputation: 1387

Programmatically check if a COM port exists in C#

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?

Upvotes: 1

Views: 10133

Answers (3)

Smith
Smith

Reputation: 5959

Here is another way

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

Upvotes: 1

Kevin S. Miller
Kevin S. Miller

Reputation: 974

One-liner :

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

Upvotes: 0

Reticulated Spline
Reticulated Spline

Reputation: 2012

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

Upvotes: 4

Related Questions