user66222
user66222

Reputation: 37

C# string won't concatenate

// 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.

Upvotes: 0

Views: 2698

Answers (5)

Mike Powell
Mike Powell

Reputation: 5924

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").

Upvotes: 5

Steve Wranovsky
Steve Wranovsky

Reputation: 5723

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.

Upvotes: 4

Henk Holterman
Henk Holterman

Reputation: 273854

I'll have a guess:

The received string includes a '\0' terminator. You ought to be able to check that with the debugger.

Upvotes: 3

Frederik Gheysels
Frederik Gheysels

Reputation: 56984

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.

Upvotes: 2

jhunter
jhunter

Reputation: 1892

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

returndata = string.Concat(returndata, "test");
returndata += "test";

Upvotes: 5

Related Questions