access to the port 'com3' is denied

May 24 2017 6:03 PM
I have a serial port in my form (c# winform). When I load my form, it runs the code serialport1.open(); And it works fine, I can get what I need from serial port however when I reload the form, it gives me the error "Access to the port 'COM3' is denied." I tried to use if serialport1.IsOpen() then serialport1.close(); But it didn't work. Serial port is accessible and works fine. It just gives me that error. How can I solve this problem? here's my code..
 
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace TestRFID
{
public partial class Form1 : Form
{

private string DispString;


public Form1()
{
InitializeComponent();
DispString = null;
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 9600;
}


private void button1_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
  serialPort1.Close();
}

serialPort1.Open();

serialPort1.DataReceived += new SerialDataReceivedEventHandler(RFID_DataReceived);
serialPort1.Write("1");

}

private void RFID_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
DispString = serialPort1.ReadExisting();
DispString = DispString.Replace("\r\n", "");
this.Invoke(new EventHandler(DisplayText));
serialPort1.Close();
}

private void DisplayText(object sender, EventArgs e)
{
this.Hide();
Form2 ui = new Form2(DispString);
ui.ShowDialog();
}


}
 

Answers (1)