I need to check for available COM ports in my application:
I created two ways to do this.
Method 1:
public List<string> GetAllPortsForeach()
{
var allPorts = new List<string>();
foreach (String portName in System.IO.Ports.SerialPort.GetPortNames())
{
allPorts.Add(portName);
}
return allPorts;
}
Method 2:
public List<string> GetAllPortsForLoop()
{
var allPorts = new List<string>();
for (int i = 1; i <= 16; i++)
{
string comPortName = "COM" + Convert.ToString(i);
SerialPort sp = new SerialPort(comPortName);
try
{
sp.Open();
allPorts.Add(comPortName);
sp.Close();
}
catch
{
}
}
return allPorts;
}
Which is the fastest? Which should I use and why?