-3

Possible Duplicate:
How to read a text file reversely with iterator in C#

I need to read txt file more than 7 million lines from bottom to the top by just following line of code: I was wondering is the right way or shall i use iterator for this task? Some answers using iterator already in stackoverflow.

        foreach (string line in File.ReadAllLines("read.txt").Reverse())
        {            
            Console.WriteLine(line);
        }
Community
  • 1
  • 1
MMK
  • 3,673
  • 1
  • 22
  • 30
  • @ThomAS please read my question i have alread visited the links, i am not asking for answer just suggestion. – MMK Nov 30 '12 at 08:48
  • 1
    Defer micro-optimisation until you reach performance problems, the benchmark. – John Dvorak Nov 30 '12 at 08:49
  • @JanDvorak while thats good advice, the question is still valid in terms of how to do it. Which is answered really well in the linked duplicate just above – Keith Nicholas Nov 30 '12 at 08:51
  • The post http://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c-sharp explains another, more performant but more error prone way. Regarding "the right way to do it": Does it work for you currently? I second @JanDvorak opinion. – Th 00 mÄ s Nov 30 '12 at 08:55
  • @ThomAS Error prone way, then why its in the framework? – MMK Nov 30 '12 at 08:57
  • @MMK Edited my post to make clear which post iam reffering to. Sorry for the confusion. Ofcourse "File.ReadAllLines" is not error prone. – Th 00 mÄ s Nov 30 '12 at 09:00

1 Answers1

0

As files are not line based, there is no convenient way to read lines from the end of the file. What you are doing works fine, as long as the entire file fits in memory.

If you run into memory problems, you can read the file in chunks, e.g. File.ReadLines(path).Skip(6000000), then File.ReadLines(path).Skip(5000000).Take(1000000). This will read the file up to that point every time, but it will use less memory.

Another alternative would be to read chunks of bytes from the file, locate the line breaks in the bytes, and decode the bytes between them into strings.

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