Pages

Thursday, March 29, 2012

LINQ to Text Files

LINQing it

If you ever need to find something specific inside a text file, I'd advise you to go with LINQ.
Below is a very useful extension method to work with Text Files' content with LINQ:

static class Extensions
{
    public static IEnumerable<string> Lines(this StreamReader reader)
    {
        string line;
        
        while (!string.IsNullOrEmpty(line = reader.ReadLine()))
        {
            yield return line;
        }
    }
}

So with the above extension method in context, you could simply do things like this:


using (var sr = new StreamReader(myPath))
{
    var results = from line in sr.Lines()
                  where line.StartsWith("Foo") && line.Contains("this text")
                  select line;
}

This makes life a little easier.