1
votes

I have a need to send bytes through the serial port and wanted to do this using the convenience of the C# class SerialPort. However it apperas there is a severe restriction on sending raw bytes through the serial port using this class as, quoting from the ASCIIEncoding class docs:

ASCIIEncoding corresponds to the Windows code page 20127. Because ASCII is a 7-bit encoding, ASCII characters are limited to the lowest 128 Unicode characters, from U+0000 to U+007F. If you use the default encoder returned by the Encoding.ASCII property or the ASCIIEncoding constructor, characters outside that range are replaced with a question mark (?) before the encoding operation is performed.

This is NOT what I want. If I have a byte value greated than 0x7F I want it sent as that value, NOT encoding as a question mark. I cannot use UTF-8 encoding as this can introduce more bytes for characters which my receiving device does not expect. Both SerialPort.Write Method (Char[], Int32, Int32) and (stupidly in my opinion) SerialPort.Write Method (Byte[], Int32, Int32) encode the data prior to transmission.

It appears that I can create my own EncoderFallback class but from my understanding this only allows me to specify another character to use instead of '?' or am I incorrect in assuming this?

So is it at all possible to send bytes that have NOT been interferred with via the SerialPort class?

1
SerialPort will send raw bytes, if you do not encode them then you won't get question marks or anything else.Adriano Repetti
I think that is a property of the serial port. IOW nothing you can do about it.leppie
I mean: the Serial.Port(byte[], int, int) shares the Remarks section with other overloads but the paragraph about encoding applies only to methods that works with strings, not with raw bytes.Adriano Repetti

1 Answers

3
votes

There's a comment on the byte[] overload page:

The remarks about ASCIIEncoding and the other types of encoding do not apply to this overload. This overload uses byte arrays, bypassing the encoding.

(It looks like these encoding remarks were copy/pasted from the other overloads of Write. Those overloads - using character arrays and strings - do use the encoding).

— Micah Copple (possibly user mjcopple - should be able to 'forward' reputation!)