Reputation: 523
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
Upvotes: -1
Views: 370
Reputation: 411
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
}
}
Upvotes: 0
Reputation: 942227
Well, no, virtual serial ports are emulated by software. If that software fails then of course there's no functional serial port anymore. Nothing you can do about that other than finding better software.
If this is the common failure mode, jerking out the connector of a USB device while a program is talking to it then just don't bother. Whomever does that needs to be learned the Hard Way that using the Windows "Safely Remove Hardware" tray icon option is not optional. It tends to take a bit of reinforcement to get them to realize what "Unsafely Remove Hardware" does. Albeit, oddly, that it tends to be programmers that do this, rarely regular users. Could be site bias and regular users just tend to figure out by themselves that doing this isn't a good idea. It isn't, these drivers count on humans being cooperative. Necessary since serial ports are not plug & play devices, there's no way for the driver to deliver a "device is gone, stop using" notification. Well, other than hard-crashing your program intentionally.
Upvotes: 1
Reputation: 3309
Put it in a try - catch statement and print a message to the user if something bad happened.
try
{
SerialPort SerialPort1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
SerialPort1.Open()
SerialPort1.DataReceived += new SerialDataReceivedEventHandler(...)
}
catch(Exception e)
{
//Print error to user
}
For finer granularity on the exception, see the msdn documentation of the serial port here.
Upvotes: 1