-1

我在 C# 中使用 System.IO.Ports.SerialPort 类。从位于不同 dll 中的帮助程序类打开串行端口时引发 UnAuthorizedAccessException。如果端口是从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); 
    }
} 
4

2 回答 2

0

已经在 COM1 上打开了一个端口

谢谢

于 2013-11-02T11:42:18.410 回答
-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();
    }
}
于 2016-04-10T09:55:33.830 回答