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.

1

2 Answers 2

10
File.ReadAllLines(@"C:\test.txt").Reverse() 
Sign up to request clarification or add additional context in comments.

5 Comments

Great, mine is nonsense and will be deleted.
@SharrokG Fine, so be nice, accept his answer and give him the points. ;-)
how can i use this in my code to read reverse can u pls say me
@SharrokG, I take it you've never used C# before? Try this: var reversedLines = File.ReadAllLines(@"C:\test.txt").Reverse(); foreach (var line in reversedLines) DoSomething(line); where you write the DoSomething part.
Too bad answer for performance wise..
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(); 

2 Comments

Joe Whites solution is much better, because it uses only one file access.
I suggest to try with a file sized a couple of Gigabytes...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.