尝试在 C# 中打开 com 端口时出现 UnauthorizedAccessException [英] UnauthorizedAccessException when trying to open a com port in C#

查看:175
本文介绍了尝试在 C# 中打开 com 端口时出现 UnauthorizedAccessException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Arduino 板在串行 COM 端口上写入数据,并使用 C# 应用程序读取它.但是每当我尝试运行 C# 程序时,它尝试打开串行端口时都会发生异常 (UnauthorizedAccessException).如何正确打开串口?

I am using an Arduino Board to write on the Serial COM port, and using a C# app to read it. But whenever I try to run the C# program, an exception (UnauthorizedAccessException) occurs when it tries to open a serial port. How do I properly open a serial port?

我对C++知之甚少.我的大部分知识来自它们与 C++ 的相似之处,以及大量的谷歌搜索教程.这是我从我找到的教程之一中复制的代码之一:

I have very little knowledge in C++. Most of my knowledge comes from their similarities with C++, and a lot of googling tutorials. 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);
        }
    }
}

推荐答案

发生的情况是您已经在另一个应用程序中打开了 COM3(请参阅 MSDN).当您单击 button1 时,程序可以看到 COM 端口已打开(在另一个应用程序中)并尝试写入它,即使您的程序无权访问它.

What is happening is that you have COM3 already open in another application (See 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.

首先,您需要创建一个串行端口实例(我怀疑您已经这样做了,因为您会收到不同的错误).我在创建 Form1 时创建了我的实例:

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:

    public Form1()
    {
        InitializeComponent();

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

在下面我将 button2 重命名为 openPortButton:

In the following I have renamed button2 to 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();
        } 

您还可以通过将串行端口包装在 try-catch 语句中来捕获打开串行端口时的任何异常:

You can also catch any exceptions when opening the serial port by wrapping it inside a try-catch statement:

        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;
        }
    }

其中 commsEstablished 是 Form1 中的私有 bool.

Where commsEstablished is a private bool in Form1.

现在当按下发送按钮时,测试 commsEstablished 变量:(我也将 button1 重命名为 sendButton)

Now when the send button is pressed test the commsEstablished variable: (I have also renamed button1 to 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
            }
        }
    }

这篇关于尝试在 C# 中打开 com 端口时出现 UnauthorizedAccessException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆