c# - TextReader.Peek 行为和检测流/阅读器的结尾

标签 c# .net textreader

当我使用文本阅读器时,检测我实际上已到达数据末尾的最佳方法是什么?执行此操作的常用方法是类似以下内容,

    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() 你会得到一个否定的结果。

使用 BinaryReaderthe 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/

相关文章:

Java文本输入: How to ignore lines starting with certain characters in them?

c# - VB6 到 C# InsTR 函数转换问题

c# - 函数参数中的空指针与对象

c# - 如何在调用 Process.GetProcessById 之前检查进程是否仍在运行?

.net - 至少有潜在危险的错误,你会怎么做?

c# - 在 TextReader 上实现 ReadKey()

c# - 数据绑定(bind)、多线程和单元测试

C# 正则表达式匹配一行中的精确字符串但忽略大小写

c# - asp.net mvc中依赖解析和IoC的优势

c# - TextReader 类行数