1

I am developing a program to communicate with an old system. I use System.IO.Ports.SerialPort for this. The problem is when I send a longer message, the message bevome corrupt. I use a line listener and get the following results

What I sending

aa 01 00 00 12 03 06 18 02 c1 94 02 c1 94 00 00 00 00 00 00 00 00 00 00 00 00 1e fd 

What I get

c2 aa 01 00 00 12 03 06 18 02 c3 81 c2 94 02 c3 81 c2 94 00 00 00 00 00 00 00 00 00 00 00 00 1e c3 bd

The code I'm using is

_comPort.Encoding = new UTF8Encoding();
_comPort.PortName = PortName;  //Com1
_comPort.BaudRate = BaudRate;  //9600
_comPort.StopBits = StopBits;  //1
_comPort.DataBits = DataBits;  //8
_comPort.Parity   = Parity;    //None
_comPort.Open();

_comPort.Write(messageStr);

Why is data corrupted and how do I fix this?

magol
  • 6,135
  • 17
  • 65
  • 120
  • Don't store binary data in string. SerialPort.Write() does *not* encode in ascii when you pass a byte[], no encoding is necessary for bytes. – Hans Passant Aug 17 '11 at 13:00

1 Answers1

4

My guess is that messageStr is a string, and you're seeing encoding issues. You've explicitly specified the UTF-8 encoding, so that's what you're getting - but I suspect it's not what you really want.

You've shown binary data, so I assume you actually want to send exactly that binary data - in which case you should use the Write(byte[], int, int) overload.

If you really want to write text data, you probably just need to pick the right encoding - but you'll need to give us more information for us to help you make the right choice.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yes, it is binary data that I want to send. The problem is that both Write(byte[], int, int) and Write(string) as default use ASCIIEncoding to encode characters, and then it can not handle characters larger than 127 (0x7F). And I have several bits that are bigger than that. That's why I changed Encoding. What Encoding should I have instead? – magol Aug 17 '11 at 12:53
  • @magol If that is true, you may need to use base-64 (Convert.ToBase64String); however, I would expect Write(byte[], ...) to write binary – Marc Gravell Aug 17 '11 at 12:58
  • As shown in the manual for the Write (byte [], int, int), do I need Encoding. But I'll try. – magol Aug 17 '11 at 12:59
  • @magol: These are *bytes*, not characters. I realize the remarks section of `Write` talks about encodings, but I don't think it really should. Have you tried using `Write(byte[]...)` already? It would be really weird if that applied any encoding at all. (I think it's a mistake that that's even mentioned on the page.) Conceptually there are no characters here, just bytes, so the encoding shouldn't be relevant. – Jon Skeet Aug 17 '11 at 12:59
  • You are right. Write(byte[], int, int) does not care about Encoding. Thank you very much for your help :-) – magol Aug 17 '11 at 13:54