刚刚发现了这个帖子,想要分享我的发现:我也担心在Mac上会出现这种情况。在Windows和Linux(无论是在VS还是Mono中),SerialPort.GetPortNames()都会返回一个列表,并遵循以下规则:
1)Windows返回一个字符串列表,例如Com1、Com4,省略任何不存在的端口(USB串行适配器似乎会根据插入的插头取一个COM号码,始终如一)。从我的串口扫描器中可以看到:
正在扫描COM1
正在扫描COM4
扫描完成
2)Linux返回所有可能由Linux发行版编译器启用的tty串行端口。这似乎是大约8个端口,如果您尝试打开它们,将会抛出异常(从我的串口扫描器中可以看到:
正在扫描 /dev/ttyS0
正在扫描 /dev/ttyS1 端口失败System.IO.IOException: I/O 错误
at System.IO.Ports.SerialPortStream..ctor (System.String portName, Int32 baudRate, Int32 dataBits, Parity parity, StopBits stopBits, Boolean dtrEnable, Boolean rtsEnable, Handshake handshake, Int32 readTimeout, Int32 writeTimeout, Int32 readBufferSize, Int32 writeBufferSize) [0x00000]
at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPortStream:.ctor (string,int,int,System.IO.Ports.Parity,System.IO.Ports.StopBits,bool,bool,System.IO.Ports.Handshake,int,int,int,int)
at System.IO.Ports.SerialPort.Open () [0x00000]
at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:Open ()
at HSMScanner.Program.Main (System.String[] args) [0x00000]
正在扫描 /dev/ttyS2 端口失败System.IO.IOException: I/O 错误
at System.IO.Ports.SerialPortStream..ctor (System.String portName, Int32 baudRate, Int32 dataBits, Parity parity, StopBits stopBits, Boolean dtrEnable, Boolean rtsEnable, Handshake handshake, Int32 readTimeout, Int32 writeTimeout, Int32 readBufferSize, Int32 writeBufferSize) [0x00000]
at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPortStream:.ctor (string,int,int,System.IO.Ports.Parity,System.IO.Ports.StopBits,bool,bool,System.IO.Ports.Handshake,int,int,int,int)
at System.IO.Ports.SerialPort.Open () [0x00000]
at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:Open ()
at HSMScanner.Program.Main (System.String[] args) [0x00000]
正在扫描 /dev/ttyS3 端口失败System.IO.IOException: I/O 错误
at System.IO.Ports.SerialPortStream..ctor (System.String portName, Int32 baudRate, Int32 dataBits, Parity parity, StopBits stopBits, Boolean dtrEnable, Boolean rtsEnable, Handshake handshake, Int32 readTimeout, Int32 writeTimeout, Int32 readBufferSize, Int32 writeBufferSize) [0x00000]
at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPortStream:.ctor (string,int,int,System.IO.Ports.Parity,System.IO.Ports.StopBits,bool,bool,System.IO.Ports.Handshake,int,int,int,int)
at System.IO.Ports.SerialPort.Open () [0x00000]
at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:Open ()
at HSMScanner.Program.Main (System.String[] args) [0x00000]
3) Macs...
哦,亲爱的。当USB串口插入并且驱动程序和一切都正常时,Mac电脑在GetPortNames()上不返回任何东西。在/dev/tty中查看,只有在设备插入并且具有类似于/dev/tty.usbserial-A7006Ro7的名称时,额外的设备才会出现,不幸的是,将此名称用作程序的参数,然后跟随serial.open似乎没有任何效果。
进一步研究。