问题
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