检查是否有串口

Check if there are Serial ports

我正在使用此代码检测所有可用的串行端口:

foreach (string PortName in System.IO.Ports.SerialPort.GetPortNames())
{
    PortBox.Items.Add(PortName);
}

如果没有串口,有没有办法MessageBox.Show("Could not find any ports");

GetPortNames() returns 一个数组。将此数组存储为变量,然后检查它是否有 Length 零。

string[] portNames = System.IO.Ports.SerialPort.GetPortNames();
if (portNames.Length == 0)
{
    // No serial ports - do whatever
}