File.ReadAllLines() vs StreamReader

A couple of days ago I forced myself to memorize the C# code for reading from a file (text, html), and for it I used the StreamReader class (on MSDN):

try
{
    using(StreamReader reader = new StreamReader('filename'))
    {
            string s;
            while((s = reader.ReadLine()) != null)
            {
                   Console.WriteLine(s);
            }
     }
}
catch(Exception ex)
{
      Console.WriteLine(ex.Message);
}

This is in comparison to the File class which has a method called ReadAllLines, and its biggest benefit is that it results in less code. Is less more? I’m not sure yet. With the StreamReader class you can create a method that implements IEnumerable which allows you to use the foreach on it. I found the sample for this on http://stackoverflow.com/questions/286533/filestream-streamreader-problem-in-c.

public static IEnumerable ReadLines(string path)
    {
        using (StreamReader reader = File.OpenText(path))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }

foreach(string line in ReadLines(file))
{
    Console.WriteLine(line);
}

It is also mentioned that the StreamReader approach works nicely with Linq. Another thing that was mentioned is that the StreamReader uses a concept called lazy evaluation and this increases performance.

Does the less code option result in better performance just because it uses less lines of code? I’m a bit undecided. Maybe I will have a better opinion in the future.

  • Share/Bookmark

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes