[英]Programmatically check if a COM port exists in C#
I just got myself into using the SerialPort object in C# and I realised it throws an exception saying that "COM1" does not exist. 我只是开始使用C#使用SerialPort对象,我意识到它引发了一个异常,说“ COM1”不存在。 I checked my device manager to see what COM ports I can use, but is there a way to find out what COM ports are available and programmatically select one of them?
我检查了设备管理器以查看可以使用哪些COM端口,但是有没有办法找出可用的COM端口并以编程方式选择其中一个?
Yes, use SerialPort.GetPortNames()
, which returns an array of strings of available port names. 是的,使用
SerialPort.GetPortNames()
,它返回可用端口名称的字符串数组。
Then create your SerialPort
object by specifying one of the names in the constructor. 然后通过在构造函数中指定名称之一来创建
SerialPort
对象。
string[] ports = SerialPort.GetPortNames();
SerialPort port = new SerialPort(ports[0]); // create using first existing serial port, for example
One-liner : 单线:
if(SerialPort.GetPortNames().ToList().Contains(comportName))
{
port = new SerialPort(comportName)
}
这是另一种方式
string portExists = SerialPort.GetPortNames().Any(x => x == "COM1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.