I have a strange problem. I am getting a stream of text from a tcp client and writing it to a file. The stream is not fully filled hence while converting it to string the unfilled parts of the byte array are converted to \0 so i finally end up having,
str = "blah foo bar \0\0\0\0\0...";
so what i did is
str = str.trim('\0');
But if i do this then the string is not getting written to a file using stream writer. If i comment the trim line then its getting written along with all the white space characters. Here is my full code
StreamWriter sw = new StreamWriter("c:\\a\\ta.txt");
while (true)
{
try
{
NetworkStream ns = tc.GetStream();
byte[] instream = new byte[tc.ReceiveBufferSize];
Thread.Sleep(2500);
ns.Read(instream, 0, tc.ReceiveBufferSize);
string decodedData = string.Empty;
decodedData = System.Text.Encoding.ASCII.GetString(instream);
decodedData = decodedData.Trim('\0');
//string a = "dfdsfdsfdsfdsf";
//string b = a.Trim('\0');
try
{
sw.Write(decodedData);
//MessageBox.Show(decodedData);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Can some one explain me why this is and how i can solve htis out.
oh on debugging i can see that decodedData has the trimmed text neat and clean but i dont know why its not being written to the file.
There are three problems here.
First, you grab the text from the whole array, regardless of how many bytes you actually did receive. Most likely this is the source of your zero characters.
To fix that, change the code as follows:
Secondly, you need to close the stream in order for it to flush its contents. The best way to do that is to wrap it in a
usingblock:Thirdly, the code would normally never complete. Add a way for it to complete without relying on exception handling, for instance: