简体   繁体   English

尝试在C#中打开com端口时出现UnauthorizedAccessException

[英]UnauthorizedAccessException when trying to open a com port in C#

I am using an Arduino Board to write on the Serial COM port, and using a C# app to read it. 我正在使用Arduino开发板在串行COM端口上进行写入,并使用C#应用程序来读取它。 But whenever I try to run the C# program, an exception (UnauthorizedAccessException) occurs when it tries to open a serial port. 但是,每当我尝试运行C#程序时,尝试打开串行端口时都会发生异常(UnauthorizedAccessException)。 How do I properly open a serial port? 如何正确打开串行端口?

I have very little knowledge in C++. 我对C ++知之甚少。 Most of my knowledge comes from their similarities with C++, and a lot of googling tutorials. 我的大部分知识都来自于与C ++的相似之处以及许多使用Google搜索的教程。 Here is one of the codes that I copied from one of the tutorials I found: 这是我从发现的其中一篇教程中复制的代码之一:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if(!serialPort1.IsOpen)
        {
            serialPort1.PortName = "COM3";

            serialPort1.Open();

            richTextBox1.Text = "opened";
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if(serialPort1.IsOpen)
        {
            string text = richTextBox1.Text;
            serialPort1.WriteLine(text);
        }
    }
}

What is happening is that you have COM3 already open in another application (See MSDN ). 发生的事情是您已经在另一个应用程序中打开了COM3(请参阅MSDN )。 When you click on button1 the program can see that the COM port is open (in another application) and tries to write to it, even though your program does not have access to it. 当您单击button1时,程序可以看到COM端口处于打开状态(在另一个应用程序中),并尝试对其进行写操作,即使您的程序无法访问它也是如此。

Firstly you will need to create an instance of the serial port (which I suspect you have already done since you would receive different error). 首先,您将需要创建一个串行端口实例(我怀疑您已经完成此操作,因为您会收到其他错误)。 I create my instance when Form1 is created: 创建Form1时创建实例:

    public Form1()
    {
        InitializeComponent();

        // Create an instance of a serial port
        serialPort1 = new SerialPort();
    }

In the following I have renamed button2 to openPortButton: 在下面的代码中,我将button2重命名为openPortButton:

    private void openPortButton_Click(object sender, EventArgs e)
    {

You could make your program aggressive by closing the serial port if it is already open: 您可以通过关闭串行端口(如果已打开)来使程序更具攻击性:

        // Check if the serial port is already open. If it is close it down first.
        if (serialPort1.IsOpen == true)
        {
            serialPort1.Close();
        } 

You can also catch any exceptions when opening the serial port by wrapping it inside a try-catch statement: 通过将串行端口包装在try-catch语句中,您还可以捕获任何异常:

        if(!serialPort1.IsOpen)
        {
            serialPort1.PortName = "COM3";

            try
            {
                serialPort1.Open();
            }
            catch
            {
                // Add exception handling here
            }
        }

Then test that the serial port is actually open: 然后测试串行端口是否真正打开:

        // Test connection
        if (serialPort1.IsOpen == true)
        {
            richTextBox1.Text = "opened";
            commsEstablished = true;
        }
        else
        {
            richTextBox1.Text = "not successful";
            commsEstablished = false;
        }
    }

Where commsEstablished is a private bool in Form1. commsEstablished是Form1中的一个私人布尔。

Now when the send button is pressed test the commsEstablished variable: (I have also renamed button1 to sendButton) 现在,当按下发送按钮时,请测试commsEstablished变量:(我也将button1重命名为sendButton)

    private void sendButton_Click(object sender, EventArgs e)
    {
        if(commsEstablished && serialPort1.IsOpen)
        {
            string text = richTextBox1.Text;
            try
            {
                serialPort1.WriteLine(text);
            }
            catch
            {
                // Add exception handling here
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM