从 StreamReader 获取剩余内容
我有一个流读取器,用于从流中读取行。这很好用,但是我希望能够获得最后一行,该行永远不会以换行符结束,因此 readLine() 不会捕获它。
我将把它存储为一个全局变量,并在下次运行之前附加到流中。
这有可能吗?
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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ReadLine
确实捕获流的最后一行,即使后面没有换行符。例如:打印:
ReadLine()
将仅在到达流末尾并返回全部时返回null
> 的数据。ReadLine
does capture the final line of the stream even if it doesn't have a line-break after it. For example:Prints:
ReadLine()
will only returnnull
when it's reached the end of the stream and returned all of the data.除非您确实需要逐行执行此操作,否则您可以取消整个循环并仅使用 StreamReader.ReadToEnd 方法。这将为您提供当前缓冲区中的所有内容。
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.