I'm writing a small piece of code that would determine which serial ports on a computer are free for connection. This is done by looping through the different serial ports and calling the Open() method. If an exception occurs, this indicates that the port is unavailable.
However visual studios is telling me that I'm not disposing of the object properly, or disposing it too many times if I place the dispose method within the finally block. What is the best way of disposing the serial port object, and is it wise to create a new serial port object in the for or leave it how it is?
The commented section with the question marks is the bits that I'm unsure about.
public static void QueryOpenPorts(out string[] portNames, out bool[] isOpen)
{
// serial port object used to query
SerialPort serialPort = new SerialPort();
// get valid ports on current computer
portNames = SerialPort.GetPortNames();
// number of valid ports
int count = portNames.Length;
// initialise isOpen array
isOpen = new bool[count];
// iterate through portNames and check Open()
for (int i = 0; i < count; i++)
{
// set port name
serialPort.PortName = portNames[i];
// attempt to open port
try
{
serialPort.Open();
// port available
isOpen[i] = true;
}
catch (Exception ex)
{
// serial port exception
if (ex is InvalidOperationException || ex is UnauthorizedAccessException || ex is IOException)
{
// port unavailable
isOpen[i] = false;
}
}
finally
{
// // close serial port if opened successfully ????????????
// if (serialPort.IsOpen)
// {
// serialPort.Close();
// }
}
}
// release object ?????????
// serialPort.Dispose();
}