0

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?

Max
  • 12,622
  • 16
  • 73
  • 101

1 Answers1

3

The 1st one. It reads all available port names from registry. To be more precise, it is just enough to use SerialPort.GetPortNames, if you're not planning to add any custom port name to the list.

The 2nd one:

  • limited by port number (port name can be "COM20", but the total numbers of ports in the system will be, e.g., 4)
  • exception-based (this is ugly and slower).
Dennis
  • 37,026
  • 10
  • 82
  • 150
  • even faster would be `new List(SerialPort.GetPortNames())` or the `SerialPort.GetPortNames().ToList()` LINQ method – fbstj May 15 '13 at 10:40
  • 1
    @FallingBullets: it won't, because `List` ctor in fact does the same things inside (of course, if you're not calculating processor cycles). At the same time, exceptions are really slow. – Dennis May 15 '13 at 10:47
  • ok, faster was the wrong word, but it's slightly cleaner code. – fbstj May 15 '13 at 11:53