C# access denied when trying to access communications port?

戏子无情 提交于 2019-12-11 08:56:43

问题


I'm trying to make a simple Windows Form Application in Visual Studios that will allow me to control the brightness setting of an LED strip hooked up to an Arduino.

The programming inside the Arduino is already well and done, but the C# programming is what's giving me trouble.

When trying to send strings of information through the port, I receive the following message:

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.dll . Additional information: Access to the port 'COM3' is denied.

Here is the piece of code that is giving me trouble:

  private void trackBar1_Scroll(object sender, EventArgs e)
    {    
        String color = trackBar1.Value.ToString();

        System.IO.Ports.SerialPort myPort = new System.IO.Ports.SerialPort("COM3");
        if (myPort.IsOpen == false){
         //if not open, open the port
            myPort.Open(); // Error is shown here.
        }
        if (myPort.IsOpen){
            myPort.WriteLine(color);
        }
    }

I haven't included any closing of the port because first I want to get this to work, and I'm not understanding what's going on. I'm pretty sure no other applications are using the port; the Arduino is plugged in to it via USB in order to receive it's power but other than that, it's not receiving or transmitting from any other process.

I've tried changing the port from COM3 to other ports, which is one of the main solutions given for similar questions, but still I get the same result.

Thanks for the help.


回答1:


The most common cause of Access Denied errors on COM ports is the COM port already being opened by some other program. You can use portmon to see which program that is. It could well be your own program since you never properly close the port.




回答2:


This was answered in one of the comments by N.K: Make sure the Serial Monitor is not working.



来源:https://stackoverflow.com/questions/31104809/c-sharp-access-denied-when-trying-to-access-communications-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!