[英]Fastest way checking for COM ports
I need to check for available COM ports in my application: 我需要检查应用程序中可用的COM端口:
I created two ways to do this. 我创建了两种方法来做到这一点。
Method 1: 方法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: 方法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?
我应该使用哪个?为什么?
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. 更准确地说,如果您不打算在列表中添加任何自定义端口名称,则只需使用
SerialPort.GetPortNames
即可。
The 2nd one: 第二个:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.