10

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.

user1702369
  • 1,089
  • 2
  • 13
  • 31

1 Answers1

12

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
   } 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215