Enumerating the lines of a file

If you've done any programming at all, you'll probably have read a file line by line at some point. Fortunately, most libraries provide an easy way of doing that, and .Net is no exception: the TextReader.ReadLine method provides what you need. If you've used this method, you'll have written something like the following C# code.

using( StreamReader reader = File.OpenText("myfile.txt") )
{
    string line;
    while( (line = reader.ReadLine()) != null )
    {
        // Do something with the line
    }
}

While it does the job, personally I think it would be nicer and more semantic if we could use the foreach keyword for this. It's possible of course to use File.ReadAllLines for this purpose (we can use foreach to enumerate over the array it returns), but that reads the entire file into memory at once, so it's not a good solution if the file you want to read is big.

Fortunately, we can make it possible to do this with very little code indeed, thanks to extension methods (introduced in .Net 3.5) and the yield keyword (introduced in .Net 2.0).

public static class TextReaderExtensions
{
    public static IEnumerable<string> EnumerateLines(this TextReader reader)
    {
        if( reader == null )
            throw new ArgumentNullException("reader");

        string line;
        while( (line = reader.ReadLine()) != null )
        {
            yield return line;
        }
    }
}

Note that the extension is defined on TextReader, so you're not limited to using it with StreamReader; you can also use it with StringReader or anything else that inherits from TextReader.

With these few lines of code, we can now use foreach to enumerate over the lines of a file:

using( StreamReader reader = File.OpenText("myfile.txt") )
{
    foreach( string line in reader.EnumerateLines() )
    {
        // Do something with the line
    }
}

While this isn't much shorter than the original, it looks much nicer in my opinion.

Categories: Programming
Posted on: 2008-09-26 07:25 UTC.

Comments

Christian Liensberger

2008-09-26 07:31 UTC

Nice extension method! I like the cleanness. Great idea.

Ion Todirel

2008-10-09 13:30 UTC

Yep, and if you need to use it with a for you could always use ToArray/ToList methods...

Joe Chung

2009-09-19 01:48 UTC

Ion, don't use ToArray/ToList. That's really bad advice.

Add comment

Comments are closed for this post. Sorry.

Latest posts

Categories

Archive

Syndication

RSS Subscribe