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?
-
I would guess that IsOpen only determines whether the current SerialPort instance has an open connection to the port. So it wouldn't know anything about other applications. I think the safest way is to simply try to connect, and catch that specific exception that is being thrown when it's already in use by another application.Falgantil– Falgantil2016-02-09 12:22:20 +00:00Commented Feb 9, 2016 at 12:22
-
1No, these kind of tests are never reliable on a multi-tasking operating system. If it would work that way then you'd get IsOpen = false and a microsecond later another process opens the port and your code will still fail. Also the basic reason why you can't check if a file is opened or locked. The exception is the only way. It is exceptional enough, probably very few reasons to keep your program running, so nothing to fret about.Hans Passant– Hans Passant2016-02-09 13:03:37 +00:00Commented Feb 9, 2016 at 13:03
Add a comment
|
1 Answer
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.