C# 检查是否有串行端口

C# 检查是否有串行端口,c#,serial-port,serial-communication,C#,Serial Port,Serial Communication,我正在使用此代码检测所有可用的串行端口: foreach (string PortName in System.IO.Ports.SerialPort.GetPortNames()) { PortBox.Items.Add(PortName); } 有没有办法MessageBox.Show(“找不到任何端口”)如果没有串行端口?GetPortNames()返回一个数组。将此数组存储为变量,然后检查其长度是否为零 string[] portNames = System.IO.Ports.

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

foreach (string PortName in System.IO.Ports.SerialPort.GetPortNames())
{
    PortBox.Items.Add(PortName);
}
有没有办法
MessageBox.Show(“找不到任何端口”)
如果没有串行端口?

GetPortNames()
返回一个数组。将此数组存储为变量,然后检查其长度是否为零

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

如果您还没有学到足够的知识来了解这个问题的答案,请不要使用SerialPort类。它会把你活活吃掉,吐出你的骨头。。。我只能通过问才能知道。不客气!如果你觉得我的回答解决了你的问题,你可以回答。