C#检查,如果一个COM(串口)端口已打开串口、端口、COM

2023-09-02 20:45:47 作者:浮浮沉沉嘚愛

有没有,如果已经打开/正在使用串行COM端口编程检查一个简单的方法?

通常情况下,我会用:

 尝试
{
    //打开端口
}
赶上(例外前)
{
    //处理异常
}
 

不过,我想以编程方式检查,所以我可以尝试使用其他COM端口或类似。

解决方案

我需要类似的东西前段时间,来搜索设备。

我获得可用的COM端口的列表,然后简单地遍历他们,如果它没有引发异常我试图与设备进行通信。有点粗糙,但工作。

  VAR port名字= SerialPort.GetPortNames();

的foreach(在port名字VAR港){
    //尝试为每个端口名,并打破第一个工作日
}
 

怎么查看电脑上的串口COM

Is there an easy way of programmatically checking if a serial COM port is already open/being used?

Normally I would use:

try
{
    // open port
}
catch (Exception ex)
{
    // handle the exception
}

However, I would like to programatically check so I can attempt to use another COM port or some such.

解决方案

I needed something similar some time ago, to search for a device.

I obtained a list of available COM ports and then simply iterated over them, if it didn't throw an exception i tried to communicate with the device. A bit rough but working.

var portNames = SerialPort.GetPortNames();

foreach(var port in portNames) {
    //Try for every portName and break on the first working
}