【问题标题】:Check if a StreamReader can read another line检查 StreamReader 是否可以读取另一行
【发布时间】:2012-12-04 14:31:22
【问题描述】:

我需要在阅读之前检查一行是否包含字符串,我想使用类似这样的 while 循环来执行此操作

    while(reader.ReadLine() != null)
    {
        array[i] = reader.ReadLine();
    }

这显然是行不通的,那我该怎么做呢?

【问题讨论】:

  • 您的问题需要更加明确。 “在我阅读之前检查一行是否包含字符串” - 你的意思是检查数据是否被读取还是检查该行是否包含特定的字符串?

标签: c# .net streamreader


【解决方案1】:

尝试使用Peek 方法:

while (reader.Peek() >= 0)
{
    array[i] = reader.ReadLine();
}

文档:http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspxhttp://msdn.microsoft.com/en-us/library/system.io.streamreader.peek.aspx

【讨论】:

  • 是的,这行得通,前两个答案读取了行但也消耗了它们,这正是我想要的。谢谢:)
  • 4 年后我知道了,但我想指出 Peek()StreamReader 一起使用时无法按预期工作 NetworkStream
【解决方案2】:
String row;
while((row=reader.ReadLine())!=null){
    array[i]=row;
}

应该可以。

【讨论】:

    【解决方案3】:

    StreamReader.ReadLine 从当前流中读取一行字符,同时读取器在底层 Stream 对象中的位置也提前了该方法能够读取的字符数。因此,如果您第二次调用此方法,您将从底层流中读取下一行。解决方案很简单 - 将行保存到局部变量。

    string line;
    while((line = reader.ReadLine()) != null)
    {
       array[i] = line;
    }
    

    【讨论】:

      【解决方案4】:
      while (!reader.EndOfStream)
      {
          array[i] = reader.ReadLine();
      }
      

      【讨论】:

      • 亲爱的投票者,您能解释一下为什么这个答案没有用吗?有关更多详细信息,您可以查看以下链接StreamReader.EndOfStream
      猜你喜欢
      • 2013-06-23
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      相关资源
      最近更新 更多