Sunday, June 19, 2011

C#: Read a file in reverse

Here is the method I use to display a file's contents in reverse.

// The declaration of the list object should specify that it is a list of strings but Blogger won't let me type in the angular brackets
List list = new List();
// Replace filePath with the full path of the file being read from
StreamReader read = new StreamReader(filePath);
while (!read.EndOfStream)
{
   list.Add(read.ReadLine());
}
read.Close();
list.Reverse();

2 comments:

  1. C# code example. Its my mash-up of several methods I found online for getting the contents of a file and display them line-by-line, with the last line of the file being shown first. I looked it up because I wanted to find out how to display error log messages sorted from newest entries to oldest entries.

    ReplyDelete