Free Information Technology Magazines and eBooks

Monday, June 01, 2009

How to read multiple files in a directory using LINQ

On my previous blog entries, I already have discussed How to read XML, CSV and SQL using LINQ. For my today's entry, I will try to show you another coding trick with the use of LINQ: How to read multiple files in a directory using Language Integrated Query. I also prepared a sample C# project associated to this blog entry, the download URL is posted below.


To read multiple files in a directory using LINQ:

1. Include the following namespaces on your C# project.

using System.Linq; //LINQ capability
using System.Text; //For string builder
using System.IO; //File and directory handling


2. To reading multiple files, use the following LINQ code.

var filecontent = Directory.GetFiles(@"c:\test\")
.Where(filename => filename.EndsWith(".txt"))
.Select(filename => File.ReadAllText(filename))
.Aggregate(
new StringBuilder(),
(sb, s) => sb.Append(s).Append(Environment.NewLine),
sb => sb.ToString()
);


3. Now compile and test run your project.


Here is the complete source code of the C# project

static void Main(string[] args)
{
var filecontent = Directory.GetFiles(@"c:\test\")
.Where(filename => filename.EndsWith(".txt"))
.Select(filename => File.ReadAllText(filename))
.Aggregate(
new StringBuilder(),
(sb, s) => sb.Append(s).Append(Environment.NewLine),
sb => sb.ToString()
);


Console.WriteLine(filecontent);
Console.ReadKey();
}



You can also download the C# project for this article here.

For more LINQ coding tips, subscribe now


0 comments: