Search code examples
c#streamreader

StreamReader to Read Range of lines


Lets say I have a File and want to read the lines, it is:

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

How do I read only a range of lines? Like readlines from 10 to 20 only.


Solution

  • I suggest using Linq without any reader:

      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) {
        ... 
      }
    

    In case you have to use the reader, you can implement something like this

       // 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
       }