如何从串口读取时应用编码
我正在从串口读取数据。 我看了这篇post: http : //social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/a709d698-5099-4e37-9e10-f66ff22cdd1e
他正在撰写我遇到的许多问题,但在他的写作中他提到使用:System.Text.Encoding.GetEncoding(“Windows-1252”)。 我遇到的问题是何时以及如何应用此问题。 我认为有三个地方点。 定义串口对象时:
private SerialPort comport = new SerialPort();
事件处理程序:
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
或者在阅读数据时:
string data = comport.ReadExisting();
无论我在哪里添加它。 我似乎得到了错误。 如何使用编码?
而不是使用ReadExisting
,使用端口的Read
方法获取字节,然后将它们转换为具有所需编码的字符串,如下所示:
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); }
更新:根据João的回答,这是一个更简单,仍然是C#-2.0的友好版本。 在实例化SerialPort
对象后,设置其Encoding
属性,如下所示:
port.Encoding = Encoding.GetEncoding("Windows-1252");
那么你的DataReceived方法就变成了这样:
void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort port = (SerialPort)sender; string s = port.ReadExisting(); }
您应该在发送或接收数据之前设置适当的编码,因此构造函数是一个不错的选择。
var sp = new SerialPort { Encoding = Encoding.GetEncoding("Windows-1252") };
如果在此之后仍然无法接收数据,则需要确保发送到串行端口的数据采用您指定的编码(“Windows-1252”)。