PaulWebbster
PaulWebbster

Reputation: 1540

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

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?

Upvotes: 5

Views: 4620

Answers (1)

Adil
Adil

Reputation: 148120

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.

Upvotes: 2

Related Questions