SerialPort issue transmitting Unicode characters

The managed implementation in .NET Framework 2.0 and .NET Compact Framework 2.0 supports the Encoding property that allows developers to specify the encoding they would use to transmit data over a serial port connection. The property defaults to ASCIIEncoding, which only allows ASCII characters to be transmitted. To transmit non-ASCII Unicode characters over the wire, developers may set the property to specify UTF8 or Unicode encodings. However, there is an issue in the implementation of SerialPort.ReadExisting() in V2 RTM that causes data corruption in some cases when Unicode characters are read. The issue reproduces against both NET FX 2.0 and NETCF 2.0.

To work around the issue, use SerialPort.Read instead of SerialPort.ReadExisting(). For example, if you have the following DataReceived event handler:

  private void serial_DataReceived(object o, SerialDataReceivedEventArgs e)
  {
    if (e.EventType == SerialData.Chars)
    {
      string str = m_port1.ReadExisting();
      // Process the returned string below
    }
  }

Use the following code instead:

  private void serial_DataReceived(object o, SerialDataReceivedEventArgs e)
  {
    if (e.EventType == SerialData.Chars)
    {
      int bnread = m_port1.BytesToRead;
      char[] a_char = new char[bnread];
      int nread = 0;
      nread = m_port1.Read(a_char, 0, bnread);
      string str = new string(a_char, 0, nread);
 
      // Process the returned string below
    }
  }

 

Cheers,

Anthony Wong [MSFT]

This posting is provided "AS IS" with no warranties, and confers no rights.