The simplest play I can come up with for this problem is this code:
private void button1_Click(object sender, EventArgs e) { Byte[] receivedBytes = new byte[] { 0x48, 0x65, 0x6c, 0x00, 0x6c, 0x6f }; string receivedText = Encoding.ASCII.GetString(receivedBytes); Console.Write(receivedText + ", you won't see this"); }
Output after pressing the button several times:
HelHelHelHel
Undoubtedly, now you recognize the poison tablet in the receivedBytes array, this is the presence of byte 0x00, which leads to a reduction in the output string. None of this byte falls into the Visual Studio output window.
Explaining this behavior requires a pretty deep dive into how Console.Write () works in a Winforms application and how it can generate output even if your program does not have a console. This is a long story that can hardly entertain anyone, so I will sing for the short version. If the debugging option of the Visual Studio hosting process is enabled, Console.Write () is equivalent to Debug.Write (). The debug output is intercepted by the DefaultTraceListener class, it throws OutputDebugString () to get the text in the debugger trace window. These winapi functions accept C strings, the C string ends with zero to indicate the end of the string.
There are several ways to fix this; the programmer's way is to convert the contents of the byte [] array to hex:
Byte[] receivedBytes = new byte[] { 0x48, 0x65, 0x6c, 0x00, 0x6c, 0x6f }; string receivedText = BitConverter.ToString(receivedBytes); Console.WriteLine(receivedText + ", you see this");
Output:
48-65-6C-00-6C-6F, you see this 48-65-6C-00-6C-6F, you see this 48-65-6C-00-6C-6F, you see this
Or you can take a better look at the data you are transmitting, ensuring that it is actually printed text that can be correctly converted using Encoding.ASCII