C# – SerialPort.Open() –IOException — “The parameter is incorrect.”

cnetserial-port

I have written the following code to configure the serial port when the MainForm loads. On first run it gives IOException when port is opened, stating that the parameter is incorrect. But when I re-start the application it works fine. The exception only comes when the application is run first time after starting the computer, and then it works fine till the next restart of the computer.

private void Main_Load(object sender, EventArgs e)
{
    this.serialPort1.PortName = "COM3";
    this.serialPort1.BaudRate = 9600;
    this.serialPort1.DataBits = 8;
    this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);

    this.serialPort1.Open(); //Exception comes here
    this.serialPort1.WriteLine("AT#cid=1" + System.Environment.NewLine);

}

Exeption details:

System.IO.IOException was unhandled by user code

Message="The parameter is incorrect.\r\n"
Source="System"

StackTrace:
at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
at System.IO.Ports.InternalResources.WinIOError()
at System.IO.Ports.SerialStream.set_RtsEnable(Boolean value)
at System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
at System.IO.Ports.SerialPort.Open()
at JKamdar.Main.Main_Load(Object sender, EventArgs e) in D:\Project\JKamdar\JKamdar\Main.cs:line 264
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
InnerException:

Best Answer

Please try using this.serialPort1.RtsEnable = true

Suggested based on the stack trace of your exception

at System.IO.Ports.SerialStream.set_RtsEnable(Boolean value)
at System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
at System.IO.Ports.SerialPort.Open()