These days I’m facing a problem with encoding string from an array of byte.
I use a socket to receive the data from server to a buffer, then I create a MemoryStream to read data from this buffer to a tempBuffer with a fixed length 30 to later GetString from tempBuffer.
byte tempBuff = new byte[30];
streamReader.Read(tempBuff, 0, 30);
string moTaSkill = Encoding.UTF8.GetString(tempBuff);
The I use a textBox to display this string as below:
tbSkill.Text = moTaSkill;
It always display wrong on the text box:
- When debug I see moTaSkill = “SKill of the hero”
- When display on the textBox it just “Skill of” or sometimes “Skill ” or “Skill of the”
I tried to create the tempBuffer with the length equals the length of string I will receive. But no success.
Can any one tell me some solution to fix it?
Two problems. You are forgetting to pay attention to the return value of the Read() call. It tells you how many actual bytes got copied into tempBuf. Which you should then use in the GetString() method so that you can avoid converting zeros.
Second problem is that a TCP connection provides a network stream, not a packet. It is quite unpredictable how many bytes you’ll get for each Read() call. Again, the return value tells you this. It will only match the number of bytes that were transmitted by the server by accident. You need to keep calling Read() until you get them all. Chief problem with that is that you don’t necessarily know when the reading is done. The server will need to pass some extra data so that the receiver knows. Like sending the string length first.