How to apply encoding when reading from a serial port

前端 未结 2 2073
[愿得一人]
[愿得一人] 2020-12-20 02:43

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

相关标签:
2条回答
  • 2020-12-20 03:25

    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();
    }
    
    0 讨论(0)
  • 2020-12-20 03:27

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

    0 讨论(0)
提交回复
热议问题