-11

In the documentation for SerialPort.Write in MS, says : By default, SerialPort uses ASCIIEncoding to encode the characters. ASCIIEncoding encodes all characters greater than 127 as (char)63 or '?'. To support additional characters in that range, set Encoding to UTF8Encoding, UTF32Encoding, or UnicodeEncoding.

Can anyone know how i set the Encoding of my serialport to one of that options??

Rui Oliveira
  • 13
  • 1
  • 5
  • 3
    You found SerialPort.Write method and documentation and didn't looked at all properties of SerialPort class?? Also in what you posted is already the answer - read it againt! Hint: SET ENCODING TO... – Renatas M. Sep 01 '14 at 10:34
  • http://stackoverflow.com/a/18986941/891715 – Arie Sep 01 '14 at 10:54
  • i wanted to know how, i know that the types of encoding are there. you dont understand my question – Rui Oliveira Sep 01 '14 at 14:14

2 Answers2

3

How about using System.IO.Ports.SerialPort.Encoding Property?

Like this:

Encoding enc = new UTF8Encoding(true, true);
YourPort.Encoding = enc;
mg30rg
  • 1,311
  • 13
  • 24
  • Almost, i do this: serialPort1.Encoding = Encoding.GetEncoding("Windows-1252"); – Rui Oliveira Sep 01 '14 at 14:16
  • @RuiOliveira Also if I were you I would not trust W1252. It is the technology of the last century and there is no garantee that your clients will only use characters that fit in. UTF-8 can handle every unicode character. – mg30rg Sep 01 '14 at 14:28
  • 1
    thanks for helping, i try with serialPort1.Encoding = Encoding.UTF8; and it works to, and i prefer :) – Rui Oliveira Sep 01 '14 at 14:38
  • @mg30rg and an ancient device connected through _serial port_ is supposed to support UTF-8? It all depends on the device, consult the manual for the encoding to use. – CodeCaster Sep 02 '14 at 07:12
  • @CodeCaster Ancient devices will not support W1252 either. It will work with ASCII256, which is not natively supported. – mg30rg Sep 02 '14 at 07:35
  • You cannot say what encoding a non-specified device will use, hence my remark _"consult the manual for the encoding to use"_. – CodeCaster Sep 02 '14 at 07:38
2

The answer is in the text you included in your question:

To support additional characters in that range, set Encoding to UTF8Encoding, UTF32Encoding, or UnicodeEncoding.

You most likely want to find out and apply the proper encoding, like Windows-1252 as demonstrated here.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272