Fastest way checking for COM ports

允我心安 提交于 2019-12-12 00:47:05

问题


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?


回答1:


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).


来源:https://stackoverflow.com/questions/16562726/fastest-way-checking-for-com-ports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!