如何从串口读取时应用编码

时间:2010-04-26 15:09:06

标签: c# encoding serial-port

我正在从串口读取数据。我看过这篇文章: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();

无论我在哪里添加它。我似乎得到了错误。如何使用编码?

2 个答案:

答案 0 :(得分:9)

您应该在发送或接收数据之前设置适当的编码,因此构造函数是一个不错的选择。

var sp = new SerialPort
{
    Encoding = Encoding.GetEncoding("Windows-1252")
};

如果在此之后仍然无法接收数据,则需要确保发送到串行端口的数据采用您指定的编码(“Windows-1252”)。

答案 1 :(得分:6)

不使用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();
}