我在C#中使用System.IO.Ports.SerialPort类。从我的助手类打开串口时抛出UnAuthorizedAccessException,该助手类位于不同的dll中。如果端口从win表单本身打开,则打开端口是成功的!
_portNames = new List<string>();
_portNames.AddRange(SerialPort.GetPortNames());
_serialPort = new SerialPort();
_serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
_serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(serialPort_ErrorReceived);
var index = 0;
while (!_serialPort.IsOpen && index < _portNames.Count)
{
try
{
_serialPort.PortName = _portNames[index++];
_serialPort.Open();
}
catch (Exception ee)
{
_logger.Log(ee.Message, EventLogEntryType.Warning);
}
}
答案 0 :(得分:0)
已在COM1上打开端口
感谢
答案 1 :(得分:-1)
打开端口时,应始终检查串口是否已打开。可能有另一个应用程序打开了COM端口。
在_serialPort.Open()
声明上方试用此代码:
try
{
_serialPort.PortName = _portNames[index++];
if (_serialPort.IsOpen)
{
MessageBox.Show(string.Concat(_serialPort.PortName, " is already opened by another application!"));
}
else
{
_serialPort.Open();
}
}