Question

I have a RFID devices connected to my laptop through Port COM1(Confirmed correct whereby i had using device manager). However, when i run these code in C# language. It give me an exception Access to the port "COM1" is denied. Anyone can help me to solve this problem? Below is my code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO.Ports;
using System.Threading;

namespace Testing1
{
    public class Testing1
    {
        public static SerialPort iSerialPort = new SerialPort();

        static int Main() 
        {
            string strException = string.Empty;
            string strComPort = "COM1";
            int nBaudrate=Convert.ToInt32(9600);

            int nRet = OpenCom(strComPort, nBaudrate, out strException);
            if (nRet != 0)
            {
                string strLog = "Connect reader failed, due to: " + strException; 
                Console.WriteLine(strLog);
                //return;
            }
            else
            {
                string strLog = "Reader connected " + strComPort + "@" + nBaudrate.ToString();
                Console.WriteLine(strLog);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

            iSerialPort.Close();
            return 0;
        }

        public static int OpenCom(string strPort, int nBaudrate, out string strException)
        {

            strException = string.Empty;

            if (iSerialPort.IsOpen)
            {
                iSerialPort.Close();
            }

            try
            {
                iSerialPort.PortName = strPort;
                iSerialPort.BaudRate = nBaudrate;
                iSerialPort.ReadTimeout = 200;
                iSerialPort.DataBits = 8;
                iSerialPort.Parity = Parity.None;
                iSerialPort.StopBits = StopBits.One;
                iSerialPort.Open();
            }
            catch (System.Exception ex)
            {
                strException = ex.Message;
                return -1;
            }



            return 0;
        }
    }
}
Was it helpful?

Solution

This exception can occur when some other program is accessing the COM1 port. Do you have any other program open that uses the RFID device?

You can check what programs use what ports using Portmon.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top