There are several options you can use depending if you want to read the data as a stream of bytes or as a string.
Option 1, read as bytes
(Very crude way that doesn't consider extra data read after end character)
private List<byte> receivedData = new List<byte>();
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[serialPort1.BytesToRead];
serialPort1.Read(buffer, 0, buffer.Length);
receivedData.AddRange(buffer);
if (receivedData.Contains(0x03))
{
if (NewSerialDataRecieved != null)
{
NewSerialDataRecieved(this, new SerialDataEventArgs(receivedData));
receivedData.Clear();
}
}
}
Option 2, Use the NewLine property
Let's say that you want to read strings from the COM port and your strings are separated with, for example, CR+LF.
Then you need to set the NewLine property somewhere in the code.
serialPort1.NewLine = "\r\n";
Then just read line by line and trigger your event for each line.
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string receivedData = serialPort1.ReadLine();
if (NewSerialDataRecieved != null)
{
NewSerialDataRecieved(this, new SerialDataEventArgs(receivedData));
}
}
There are of course several variants of these examples that you can use as well.