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:
Post a Comment