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