I need to check if selected COM port exist before conecting to it (It gives error) I'm using Visual Studio Express 2013 C#. Or, is there some way to hide that error?
Thanks.. ~Richard
You should be doing two things. The first is checking System.IO.Ports.SerialPort.GetPortNames()
. This will tell you if the port exists. Something like:
var portExists = SerialPort.GetPortNames().Any(x => x == "COM1");
You also need to catch exceptions when opening the port if it is already in use.
var port = new SerialPort("COM1");
try
{
port.Open();
}
catch (Exception ex)
{
// Handle exception
}
Now you need to be careful and read http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open(v=vs.110).aspx for what exceptions can be thrown by SerialPort.Open()
to make sure you handle each exception appropriately.
I'd use System.IO.Ports.SerialPort.GetPortNames
- it returns an array of valid serial port names that can be opened.
Use try/catch and use exception handling to tell your user whats wrong:
SerPort = new SerialPort("COM8");
try
{
SerPort.Open();
}
catch (Exception ex)
{
Console.WriteLine("Error opening port: {0}", ex.Message);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With