Click here to Skip to main content
15,850,753 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I am working in windows application. I am using serial COM port in my application. I am getting previous data from serial port after second scan . First time scan I got the data, second time I am recieving the same data.My code in datarecievehandler event of serial port

public static void DataReceivedHandler1(object sender, SerialDataReceivedEventArgs e)
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadLine();

indata gets same as previous data .I tried to use discardbuffer but its not helping...
If you guys have any solutions , then please let me know
Updated 30-May-14 2:16am
Herman<T>.Instance 30-May-14 7:17am    
did you close and reopen the sp port after ReadLine()?
RAHUL(10217975) 30-May-14 7:24am    
No, I am opening serial port in form load and closing in window close

This is a robust approach:

private SerialPort _serialPort;
    _serialPort = new SerialPort();
    _serialPort.DataReceived += dataReceivedHandler;

        private void dataReceivedHandler(object sender, SerialDataReceivedEventArgs args)
            if (!_serialPort.IsOpen)

            int BytesToRead = _serialPort.BytesToRead;

            byte[] data = new byte[BytesToRead];

            int NumBytes = _serialPort.Read(data, 0, BytesToRead);

            String mystring = Encoding.ASCII.GetString(data, 0, NumBytes);
Share this answer

in that case you read the complete buffer in stead of 1 line
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900