How to check if COM port exist before opening connection in Visual C#
c#, exists, port, serial-port, visual-studio
Solution
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.
Problem
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