I\'m reading data from a serial port. I read this posting: http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/a709d698-5099-4e37-9e10-f66ff22cdd1e
He is
Instead of using ReadExisting
, use the port's Read
method to get the bytes and then convert them to a string with the desired encoding, like this:
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, still-C#-2.0-friendly version based on João's answer. After you instantiate your SerialPort
object, set its Encoding
property like so:
port.Encoding = Encoding.GetEncoding("Windows-1252");
Then your DataReceived method becomes just this:
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
string s = port.ReadExisting();
}
You should set the appropriate encoding before sending or receiving data, so the constructor is a good choice.
var sp = new SerialPort
{
Encoding = Encoding.GetEncoding("Windows-1252")
};
If you still have problems receiving data after this you need to make sure that the data being sent to the serial port is in the encoding you specified ("Windows-1252").