Hi to all,
I've a string that I have to send as byte array (with a networkstream) on the network.
I use this method to convert the string to byte[]:
byte[] arr = (new ASCIIEncoding()).GetBytes(string)
then, on the client, I've to convert the byte array received to the original string, using the socket.receive method.
My problem is that I have to pass a byte[] as buffer to the receive method, but I don't know the size of the date I am receiving.
So I create an oversized buffer and use it to contain the bytes received.
Then, I've to convert my byte[] to the original string, sended from the remote server.
I use this method to convert it:
string converted = (new ASCIIEncoding()).GetString(characters)
The convertion works fine, but the end of my string is full of null characters that represent the empty part of the buffer, as this:
STRINGCONVERTED\0\0\0\0\0\0\0\0\0\0
Now I want only to remove these inutil chars from the end of the string, or use a method that permits me to create a buffer of the right size to receive the data (but I think it's impossible).
I've tried with Trim method of string class as this:
stringTrimmed = StringToAdjust.Trim( new char[] { '\\' , '0' } )
but didn't remove the bad char. I've tried also to remove only the 0 char (thinking my escape char \\ could be bad) but nothing.
Any ideas
Thank you

Convert byte array to original string after received data using the socket class
Jason N. Gaylord
About the streamreader, I had initially developed a solution using them, in fact they are more easy to use...but I'm writing a multithread application with client and server, and with streamreader.readline() my application blocks the listening thread until the arrival of data.
So I needed something to limit the listening to a predefinited time (even the data is not arrived), and networksocket.Receivetimeout give me the possibility to do this.
LilleMonster
First of all, "\0" is not composed of the characters '\\' and '0'... it's a single character escape. Try:
StringToAdjust.TrimEnd ('\0');
Second, the Socket.Receive method will return the number of bytes you received. It should be sufficient to allow you to "cut" the array appropriately.
And finally, since you are sending and receiving text strings... consider using streams instead of going the hard way. Just create a NetworkStream for your socket, then create a StreamWriter and a StreamReader out of it... it allows you to read data via a ReadLine, for instance...
HTH
--mc
abowman
byteArray.Length will return the number of bytes in the array.
Also, you can write a function to go from the end of the string to the beginning looking for a character other than \0 and stop when you hit it, and that will be the end of the string.