Home > Back-end >  Open a connection with COM1 port even if its already opened by another process in C#
Open a connection with COM1 port even if its already opened by another process in C#

Time:07-24

Am trying to read data from the COM port in C#, I need to open the connection with the COM port first. but the port I'm trying to connect with is already opened by another process and I need other processes to be opened as well. I know the connection to the COM port is exclusive only one process can open the connection. But I wonder is it possible to read data from the same port without closing the first connection I mean Like force an opening, using Spy mode, port listening, or monitoring the port. the code I use for connection is:

SerialPort sp = new SerialPort();
                sp.PortName = comboBox1.Text;
                if (!sp.IsOpen)
                {
                    sp.Open();
                }
I get this error: **Access to the port 'COM1' is denied.**
Any help or recommendations will be grateful.

CodePudding user response:

No and if you will export this to a standalone application then it would probably be best to just close the other application because when you export your code, it would be meaningless to have the second application open. If you are trying to use unity with an Arduino then just close the serial monitor or the app itself.

CodePudding user response:

It's not possible to spy on a port, however you can create a sort of a hub.
I suggest that you use a process (the only one which opens the port), which will communicate with the others using sockets. If you don't know how to do that check out these :

  • Sockets (Tcp listeners and clients)
  • Ports
  • Streams

You will use the System.Net.Socket namespace, so here's a quick starter guide to see how it works

  • Related