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

问题描述

我正在从串行端口读取数据。我看过这个帖子:



他正在写关于我遇到的许多问题,但在他的写作中,他提到使用:System.Text.Encoding.GetEncoding(Windows-1252)。我遇到的问题是什么时候和如何应用这个。我认为有三个条件。当串行端口对象被定义时:

  private SerialPort comport = new SerialPort(); 

事件处理程序:

  comport.DataReceived + = new SerialDataReceivedEventHandler(port_DataReceived); 

或阅读数据时:

  string data = comport.ReadExisting(); 

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

解决方案

而不是使用 ReadExisting 端口的读取方法获取字节,然后将其转换为具有所需编码的字符串,如下所示:

  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#基于João的答案的-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();
}


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

Or when reading the data:

string data = comport.ReadExisting();

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

解决方案

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

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

09-05 07:03
查看更多