当我使用文本阅读器时,检测我实际上已到达数据末尾的最佳方法是什么?执行此操作的常用方法是类似以下内容,
while(reader.Peek() != -1)
{
///do stuff
}
不过msdn文档here陈述如下
An integer representing the next character to be read, or -1 if no more characters are available or the reader does not support seeking.
所以我的问题是你如何判断你是否真的在读者数据的末尾,或者读者/底层流根本不支持寻找,因为这里的返回值似乎是模棱两可的?例如,如果我有以下内容
public void Parse(TextReader reader)
{
while(reader.Peek() != -1) //am I really at the end
{
//do stuff
}
}
Parse(new StreamReader(new NetworkStream(....)));
因为网络流不支持搜索。
还是我错过了什么?
编辑:
澄清一下,我可以使用更具体的 StreamReader 类轻松实现它,因为我可以检查 EoS。然而,为了让事情更通用,我想使用 TextReader,所以我不仅仅局限于 StreamReader。然而 Peek 的语义似乎有点奇怪,如果不支持搜索,为什么它不直接抛出,为此为什么 TextReader 没有 EoF 属性?
最佳答案
除非您正在使用 Peek() 查找特定值 为什么不使用 .Read()
例如
string line;
System.IO.StreamReader file = new System.IO.StreamReader(strfn);
while((line = file.ReadLine()) != null)
{
this.richTextBox1.AppendText(line+"\n");//you can replace this line to fit your UseCase
}
如果你想要一个更清晰的例子来说明如何做到这一点,你可以像我在下面发布的那样做一些可读的事情,你可以插入你自己的文本文件值并调试它以查看它是否可以工作。阅读与写作
string tempFile = Path.GetTempFileName();
using(var sr = new StreamReader("file.txt"))
{
using(var sw = new StreamWriter(tempFile))
{
string line;
while((line = sr.ReadLine()) != null)
{
if(line != "BlaBlaBla")
sw.WriteLine(line);
}
}
}
这是您可以尝试的另一种选择
从 Stream
中,如果您 Read(buffer, offset, count)
您将得到一个非正结果,如果您 Peek()
你会得到一个否定的结果。
使用 BinaryReader
,the documentation建议 PeekChar()
应该返回负值:
Return Value
Type: System.Int32 The next available character, or -1 if no more characters are available or the stream does not support seeking.
你确定这不是一个损坏的流吗?即剩余的数据不能从给定的编码形成一个完整的 char
?
关于c# - TextReader.Peek 行为和检测流/阅读器的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13650668/