C# – how to close a serialport used by another program

cserial-port

I'm writting a SerialPort program. Sometimes when I want to open the SerialPort, an UnauthorizedAccessException is thrown :access to COM1 is denied. This is beause another program( which is written by someone else and I don't have its soucecode ) is using COM1, and that program doesn't close COM1 when it exits.
I want to ask 2 questions:

  1. How to close COM1 with my code (especially C# code) when it is used
    by another program?
  2. If I cannot close COM1 with C# code, how can I close or free COM1 in Windows OS?

Thanks.

Best Answer

This Stack Overflow question is the first step: How do I get the list of open file handles by process in C#?

Once you have that, you can modify the code there to close the handle, or simply kill the process that has the handle open.

This, however, is very risky*, prone to problems, and will need to be re-engineered based on specific deployments (x32 vs x64 vs ARM) plus what 'COM1' maps to on that particular machine.

On Risk: If the serial port is being used to, for instance, install new firmware on a phone or similar - closing the port may result in bricking the device. If the port is being used to transfer data, then closing the port may result in losing data.

Good luck. But please do NOT blame me if you destroy your system or lose data.