Reputation: 11450
I have a stream reader that I am using to read lines from a stream. This works well however I would like to be able to get the last line which will never end with a line break so the readLine() will not capture it.
I will store this is a global variable and append to the stream before the next run.
Is this possible at all?
void readHandler(IAsyncResult result)
{
tcpClient = (TcpClient)result.AsyncState;
StreamReader reader ;
string line;
using (reader = new StreamReader(stream))
{
while((line = reader.ReadLine()) != null){
System.Diagnostics.Debug.Write(line);
System.Diagnostics.Debug.Write("\n\n");
}
}
getData();
}
Upvotes: 0
Views: 123
Reputation: 122674
Unless you really need to do this line by line, you could do away with this entire loop and just use the StreamReader.ReadToEnd method. That will give you everything that's currently in the buffer.
Upvotes: 0
Reputation: 1503439
ReadLine
does capture the final line of the stream even if it doesn't have a line-break after it. For example:
using System;
using System.IO;
class Test
{
static void Main()
{
string text = "line1\r\nline2";
using (TextReader reader = new StringReader(text))
{
string line;
while((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
Prints:
line1
line2
ReadLine()
will only return null
when it's reached the end of the stream and returned all of the data.
Upvotes: 1