so I have an C# WinForm that use
SerialPort SerialPort1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
SerialPort1.Open()
SerialPort1.DataReceived += new SerialDataReceivedEventHandler(...)
to listen on several Virtual COM Ports that Created by other Software(I can't control it)
So generally it goes well except When the other Software is dead or gone, the Virtual COM port it created is also gone or missing
So my WinForm App fail because there is no COM1 to listen to
Question: How should I handle this error when there is no COM port to listen
Thank you so much for your reply
If the only problem is that the number of the port is unpredictable you could detect all the available ports as shown below and the try them one at a time. I once had this problem when a usb device sometimes showed up as COM1 and other times as COM5
string[] availablePorts = SerialPort.GetPortNames();
foreach (string strPortName in availablePorts)
{
try
{
SerialPort SerialPort1 = new SerialPort(strPortName, 9600, Parity.None, 8, StopBits.One);
SerialPort1.Open();
}
catch (Exception e)
{
//Print error to user
}
}