views:

828

answers:

4
// Reads NetworkStream into a byte buffer.

NetworkStream ns;
System.Net.Sockets.TcpClient client = new TcpClient();

byte[] receiveBytes = new byte[client.ReceiveBufferSize];
ns.Read(receiveBytes, 0, (int)client.ReceiveBufferSize);
String returndata = Encoding.UTF8.GetString(receiveBytes);

I am successfully reading from a client and storing the result into a string called returndata. However, when I try to concatenate returndata with anything, no concatenation occurs. Ex: String.Concat(returndata, "test") returns returndata, as does returndata + "test".

Does anyone know why this is happening?

Edit: Steve W is correct; i found out later that returndata.Length was always returning 8192.

+5  A: 

Are you assigning it to a string or back to itself?

returndata = string.Concat(returndata, "test");
returndata += "test";
jhunter
Psychic debugging - gotta love it :)
ShuggyCoUk
+2  A: 

Strings are immutable. this means that, when you add (concatenate) another string to your string, you'll receive a new string instance.
The original string itself won't be changed.

Frederik Gheysels
+5  A: 

To expand on jhunter's answer, the Concat method doesn't alter the contents of the original string variable, it just returns the concatenated result. If you want returndata to contain the result of the concatenation, you need to use returndata = string.Concat(returndata, "test").

Mike Powell
Its not just the Concat method, NO method directly modifies strings in C#. Every string is a unique, immutable object. If you change a string, it makes a new copy.
abelenky
That's true--bad choice of words on my part.
Mike Powell
+3  A: 

I believe the problem is related to not keeping track of the total number of bytes read. Your byte buffer, set to ReceiveBufferSize, is more than likely larger than the actual number of bytes read. By taking into account the actual bytes read, and then passing it to the Encoding.UTF8.GetString() method, you should get a valid string that can be concatenated. Here's an example:


NetworkStream ns;
System.Net.Sockets.TcpClient client = new TcpClient();

byte[] receiveBytes = new byte[client.ReceiveBufferSize];
int bytesRead = ns.Read(receiveBytes, 0, receiveBytes.Length);
String returndata = Encoding.UTF8.GetString(receiveBytes,0,bytesRead);
returndata = returndata.Trim(new char[] {'\0'});

Note also the other suggestion about reading a null terminator and including it in the bytes read also could be an issue. I've included a Trim of the string to make sure null terminators are removed.

Steve Wranovsky