0

I'm using StreamReader.ReadLine() in C# to read through a text file to find the specific content like "Step-xx" and then read and use the contents that point to the next occurrence of "Step-xx+1". I know the occurrence of the "Step-xx" line is 100 lines apart in my textfile. How can I jump to line 2500 and read the contents following "Step-25", rather than reading 2500 lines and comparing it to "Step-25", which I'm doing now. I need to speed up this search.

Thanks.

  • Do you know the length of each line, or are they variable? – Matthew Haugen Mar 06 '15 at 00:50
  • possible duplicate of [How do I read a specified line in a text file?](http://stackoverflow.com/questions/1262965/how-do-i-read-a-specified-line-in-a-text-file) – PiotrWolkowski Mar 06 '15 at 00:59
  • http://stackoverflow.com/questions/1262965/how-do-i-read-a-specified-line-in-a-text-file Just refer to this link, you will find your answer – Mr.Toxy May 11 '16 at 08:46

2 Answers2

0

Files are not lines based (or even character based), so you can't skip to a specific line in a file.

If you really need to skip ahead in the file, you would need to make a guess where the 2500th line might start based on average line lengths, seek to that position and start reading. You would need to use a FileStream directly, not a StreamReader, and read the file as bytes. You would be looking for the 0x0d 0x0a byte combination that is used as newline in a Windows text file. When you have the bytes between two newlines, you can decode them into a string and look for the Step-xx markers.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Thanks for all the replies. This will do the trick.

string line = File.ReadLines(FileName).Skip(14).Take(1).First();

I need to figure out how changing from StreamReader to ReadLines would impact other things. Thanks again