How to use encoding when reading from a serial port
I am reading data from a serial port. I read this post: http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/a709d698-5099-4e37-9e10-f66ff22cdd1e
He writes about many of the problems I face, but in his letter he refers to the use of: System.Text.Encoding.GetEncoding ("Windows-1252"). The problem I am facing is when and how to apply it. In my opinion, there are three healthy places. When the serial port object is defined:
private SerialPort comport = new SerialPort();
Event handler:
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
Or when reading data:
string data = comport.ReadExisting();
No matter where I add it. I seem to be getting errors. How to use encoding?
a source to share
Instead of using, ReadExisting
use a method Read
to access the bytes and then convert them to a string with the desired encoding, for example:
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
byte[] data = new byte[port.BytesToRead];
port.Read(data, 0, data.Length);
string s = Encoding.GetEncoding("Windows-1252").GetString(data);
}
Update: Here's a simpler version with C # -2.0 support based on João's answer. After creating your object, SerialPort
set its property Encoding
like this:
port.Encoding = Encoding.GetEncoding("Windows-1252");
Then your DataReceived method will become:
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
string s = port.ReadExisting();
}
a source to share
You must set the appropriate encoding before sending or receiving data, so a constructor is a good choice.
var sp = new SerialPort
{
Encoding = Encoding.GetEncoding("Windows-1252")
};
If you are still having problems receiving data, you need to make sure that the data sent to the serial port is in the encoding you specified ("Windows-1252").
a source to share