本文介绍了如何从串口读取数据时申请编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个串口读取数据。我看了这个帖子:

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

他是写了许多我遇到的问题,但在他的写作,他是指使用:System.Text.Encoding.GetEncoding(视窗1252)。我遇到的问题是何时以及如何应用它。还有在我看来,3 potitional斑点。当串口对象定义:

He is writing about many of the issues I have encounter, but in his writing he refers to using: System.Text.Encoding.GetEncoding("Windows-1252"). The problem I'm having is when and how to apply this. There are three potitional spots in my opinion. When the serial port object is define:

private SerialPort comport = new SerialPort();



事件处理程序:

The Event handler:

comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

或读取数据时:

string data = comport.ReadExisting();



无论身在何处我添加它。我似乎得到错误。一个人怎么会用编码?

No matter where I add it. I seem to get errors. How would one use Encoding?

推荐答案

而不是使用 ReadExisting 中,使用港口的方法获取字节,然后将它们转换为字符串,与所需的编码,是这样的:

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);
}



更新:下面是一个简单的,还是C#基于若昂的回答-2.0友好的版本。当你实例化你的的SerialPort 对象,设置其编码属性,如下:

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");



那么你DataReceived方法就只是这样的:

Then your DataReceived method becomes just this:

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    string s = port.ReadExisting();
}

这篇关于如何从串口读取数据时申请编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 16:00