Linux 通过 .Net5 拒绝访问端口 'ttyUSB0',即使是 root

Linux access to the port 'ttyUSB0' is denied via .Net5 even as root

  1. 在 Debian 上,尝试访问 ttyUSB0(使用 FTDI 电缆通过 USB 串口)。
  2. 我的用户组:myuser tty dialout cdrom floppy sudo audio dip video plugdev netdev bluetooth lpadmin scanner

.Net5 代码:

System.Diagnostics.Process.Start("whoami");
var serialPort = new SerialPort("ttyUSB0", 115200);
serialPort.Open();

串行端口块:<PackageReference Include="System.IO.Ports" Version="5.0.1"/>

使用 Putty 作为我的用户或 root,我可以访问 ttyUSB0。

运行 dotnet progname.dll(作为我的用户)和 sudo dotnet progname.dll 都给我相同的结果 UnauthorizedAccessException:

**af**
Unhandled exception. System.UnauthorizedAccessException: Access to the port 'ttyUSB0' is denied.
 ---> System.IO.IOException: Unknown error 203
   --- End of inner exception stack trace ---
   at System.IO.Ports.SafeSerialDeviceHandle.Open(String portName)
   at System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
   at System.IO.Ports.SerialPort.Open()


**root**
Unhandled exception. System.UnauthorizedAccessException: Access to the port 'ttyUSB0' is denied.
 ---> System.IO.IOException: No such file or directory
   --- End of inner exception stack trace ---
   at System.IO.Ports.SafeSerialDeviceHandle.Open(String portName)
   at System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
   at System.IO.Ports.SerialPort.Open()

作为答案发布,因为它已通过评论内容解决:

是否需要在设备文件路径的开头添加/dev/使其成为/dev/ttyUSB0

然后您需要检查设备文件的所有者和权限。