1

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

I wanted to know how to read a text file from last line to first line in c#.

I am using this code for reading a text file

            using (var sr = File.OpenText("C:\\test.txt"))
            {
                string line;
                bool flag = true;
                while ((line = sr.ReadLine()) != null)
                {
                }
            }

I dont know how to read Backwards.

There would be a great appreciation if someone could help me.

Thanks In Advance.

Community
  • 1
  • 1
Sharrok G
  • 447
  • 3
  • 13
  • 27
  • 1
    Do check http://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c-sharp, it specifically mentions not reading the entire file into memory which the answers posted here so far seem to be doing. – Miserable Variable Oct 27 '11 at 12:01

2 Answers2

10
File.ReadAllLines(@"C:\test.txt").Reverse()
Joe White
  • 94,807
  • 60
  • 220
  • 330
2

Try to reverse the collection of read lines

    List<string> lines = new List<string>();
    using (var sr = File.OpenText("C:\\test.txt"))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            lines.Add(line); 
        }
    }

    lines.Reverse();
Stecya
  • 22,896
  • 10
  • 72
  • 102