Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamReader using arraylist or array

Here's my code:

StreamReader reader = new StreamReader("war.txt");
string input = null;

while ((input = reader.ReadLine()) != null)
{
    Console.WriteLine(input);
}

reader.Close();

The program above reads and prints out from the file “war.txt” line-by-line. I need to re-write the program so that it prints out in reverse order, i.e., last line first and first line last. For example, if “war.txt” contains the following:

Hello.

How are you?

Thank you.

Goodbye.

The program should prints out:

Goodbye.

Thank you.

How are you?

Hello.

I am very new in C# please help! Thanks!


1 Answers

To do that, you are going to have to buffer the data anyway (unless you do some tricky work with the FileStream API to read the file backwards). How about just:

var lines = File.ReadAllLines("war.txt");
for(int i = lines.Length - 1; i >= 0; i--)
    Console.WriteLine(lines[i]);

which just loads the file (in lines) into an array, and then prints the array starting from the end.

A LINQ version of that would be:

foreach(var line in File.ReadLines("war.txt").Reverse())
    Console.WriteLine(line);

but frankly the array version is more efficient.

like image 182
Marc Gravell Avatar answered Mar 02 '26 14:03

Marc Gravell