user5387678
user5387678

Reputation:

Can I use SerialPort.Write to send byte array

Documentation of SerialPort Write says that

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.

Also see here. Does this mean I can't send byte array using write?

Upvotes: 9

Views: 54392

Answers (2)

Dennis
Dennis

Reputation: 37770

By default, SerialPort uses ASCIIEncoding to encode the characters

You're confusing methods, which read/write strings or chars, with methods, which read/write bytes.

E.g., when you'll call this:

port.Write("абв")

you'll get "???" (0x3F 0x3F 0x3F) in the port buffer by default. On the other hand, this call:

// this is equivalent of sending "абв" in Windows-1251 encoding
port.Write(new byte[] { 0xE0, 0xE1, 0xE2 }, 0, 3)

will write sequence 0xE0 0xE1 0xE2 directly, without replacing bytes to 0x3F value.

UPD.

Let's look into source code:

public void Write(string text)
{
    // preconditions checks are omitted

    byte[] bytes = this.encoding.GetBytes(text);
    this.internalSerialStream.Write(bytes, 0, bytes.Length, this.writeTimeout);
}

public void Write(byte[] buffer, int offset, int count)
{
    // preconditions checks are omitted

    this.internalSerialStream.Write(buffer, offset, count, this.writeTimeout);
}

Do you see the difference?
Method, that accepts string, converts strings to a byte array, using current encoding for port. Method, that accepts byte array, writes it directly to a stream, which is wrapper around native API.

And yes, documentation fools you.

Upvotes: 8

dbasnett
dbasnett

Reputation: 11773

This

port.Encoding = System.Text.Encoding.UTF8;

string testStr = "TEST";

port.Write(testStr);

and this

byte[] buf = System.Text.Encoding.UTF8.GetBytes(testStr);

port.Write(buf, 0, buf.Length);

will result in the same bytes being transmitted. In the latter one the Encoding of the serial port could be anything.

The serial port encoding only matters for methods that read or write strings.

Upvotes: 2

Related Questions