Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if COM port is open by another process in C#?

Tags:

c#

serial-port

I have following problem. I've to check if the com port which I chose to use isn't used by another process in system. I try to achive that by checking the field object field IsOpen from System.IO.Ports.SerialPort but even if the port is open in another process the result is False so my program try to open the port and crash due exception. Is any other way than just handle this in try catch?

like image 830
PaulWebbster Avatar asked Oct 30 '22 09:10

PaulWebbster


1 Answers

You can call the open message and look for UnauthorizedAccessException to determine if it is free for you or not.

Access is denied to the port. - or - The current process, or another process on the system, already has the specified COM port open either by a SerialPort instance or in unmanaged code.

You will get InvalidOperationException exception if you open the port on instance that has already opened the port.

like image 147
Adil Avatar answered Nov 15 '22 04:11

Adil