c# – Checking for a COM port

Question:

How to check whether the COM port is connected or not? For example, the user selected COM 3, but during operation this port was disabled. How to correctly check if a COM port is present and is it possible to open it?

At the moment I'm doing this (example):

SerialPort port = new SerialPort("COM 8");
string[] allport = SerialPort.GetPortNames();
bool stat = false;
for (int i = 0; i < allport.Length; i++)
{
    if (allport[i] == port.PortName)
    {
        stat = true;
        break;
    }
}
if (stat)
    port.Open();
else
    Console.WriteLine("{0} отключен.", port.PortName);

But I am sure that this operation can be implemented more competently.

Answer:

As far as I understand, the port can be disabled at any time. Therefore, I would do this: work with the port as usual, and when an IOException I would tell the user about problems when communicating with the port.

You can check through

using System.IO.Ports;

var port = new SerialPort("COM99");
port.Open(); // бросает исключение, если порта нет

or

SerialPort.GetPortNames().Contains("COM99")

(how do you do it).

But catching exceptions still cannot be avoided, since the port may appear or disappear immediately after checking.

Scroll to Top