从StreamReader获取残余
本文关键字:获取 StreamReader | 更新日期: 2023-09-27 18:06:27
我有一个流阅读器,我正在使用它从流中读取行。这工作得很好,但是我希望能够获得最后一行,它永远不会以换行结束,因此readLine()将不会捕获它。
我将存储this是一个全局变量,并在下次运行之前附加到流中。
这可能吗?
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();
}
ReadLine
捕获流的最后一行,即使它后面没有换行符。例如:
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);
}
}
}
}
打印:
line1
line2
ReadLine()
将仅在到达流的末尾时返回 null
,并返回所有数据。
除非您确实需要逐行执行此操作,否则您可以去掉整个循环,只使用StreamReader。ReadToEnd方法。这会给你当前在缓冲区中的所有内容