Merge files in a directory using Linq to Objects
I have a set of txt files in a directory. I want to merge them all in to one with contects appended. How can this be ac开发者_Python百科hieved using Linq?
You can do this in .Net 4 relatively easily:
File.WriteAllLines(
outputFileName,
Directory.EnumerateFiles(inputDirectory, @"*.txt")
.SelectMany(file => File.ReadLines(file)));
You could extract this into a method:
public static void ConcatenateFiles(
string outputFileName, IEnumerable<string> inputFiles)
{
File.WriteAllLines(outputFileName, inputFiles.SelectMany(File.ReadLines));
}
Called like so:
ConcatenateFiles("test.out", Directory.EnumerateFiles(inputDirectory, @"*.txt"));
精彩评论