C# check if a COM (Serial) port is already open

前端 未结 7 1998
南旧
南旧 2020-12-05 03:27

Is there an easy way of programmatically checking if a serial COM port is already open/being used?

Normally I would use:

try
{
    // open port
}
cat         


        
7条回答
  •  抹茶落季
    2020-12-05 03:55

    I needed something similar some time ago, to search for a device.

    I obtained a list of available COM ports and then simply iterated over them, if it didn't throw an exception i tried to communicate with the device. A bit rough but working.

    var portNames = SerialPort.GetPortNames();
    
    foreach(var port in portNames) {
        //Try for every portName and break on the first working
    }
    

提交回复
热议问题