开发者

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"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜