Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 615
user1702369 Avatar asked Jul 13 '16 12:07

user1702369


1 Answers

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
   } 
like image 76
Dmitry Bychenko Avatar answered Nov 06 '22 02:11

Dmitry Bychenko