【问题标题】:StreamReader to Read Range of linesStreamReader 读取行的范围
【发布时间】:2023-03-03 11:17:01
【问题描述】:

假设我有一个文件并想读取这些行,它是:

   while( !streamReader.EndOfStream ) {
        var line = streamReader.ReadLine( );
   }

如何只读取一系列行? 仅像从 10 到 20 的 readlines。

【问题讨论】:

    标签: c# streamreader


    【解决方案1】:

    我建议在没有阅读器的情况下使用 Linq

      var lines = File
        .ReadLines(@"C:\MyFile.txt")
        .Skip(10)  // skip first 10 lines 
        .Take(10); // take next 20 - 10 == 10 lines
    
      ...
    
      foreach(string line in lines) {
        ... 
      }
    

    如果你必须使用阅读器,你可以实现这样的东西

       // read top 20 lines...
       for (int i = 0; i < 20 && !streamReader.EndOfStream; ++i) {
         var line = streamReader.ReadLine();
    
         if (i < 10) // ...and skip first 10 of them
           continue;
    
         //TODO: put relevant code here
       } 
    

    【讨论】:

    • linq 方法要优雅得多,但我会摆脱 var lines =.. 并直接循环 foreach(string line in File.Readlines...
    • 它更优雅,但它首先将整个文件读入内存,不是吗?对于较大的文件,这可能不是一个好主意...
    • @Thorsten Dittmar:不! .ReadLines 不是.ReadAllLines(请注意All
    • @DmitryBychenko - 没错,正是我的想法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多