使用c#按创建日期过滤文件

时间:2014-04-19 11:14:38

标签: c#

使用以下代码,我可以合并目录中存在的文本文件

 var allLines = Directory.GetFiles(directory, "*.txt")
                        .SelectMany(f => File.ReadLines(f));
File.WriteAllLines(outputFileName, allLines);

如何修改它以合并今天创建日期的文件?

DirectoryInfo info = new DirectoryInfo("");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();

如何组合这段代码?

3 个答案:

答案 0 :(得分:4)

使用File.GetCreationTime方法:

var allLines = Directory.EnumerateFiles(directory, "*.txt", SearchOption.TopDirectoryOnly)
                        .Where(path => File.GetCreationTime(path).Date == DateTime.Today)
                        .SelectMany(f => File.ReadLines(f));

答案 1 :(得分:3)

DirectoryInfo info = new DirectoryInfo(directory);

var allLines = info.GetFiles("*.txt")
                   .Where(p => p.CreationTime.Date == DateTime.Today)
                   .OrderBy(p => p.CreationTime)
                   .SelectMany(p => File.ReadAllLines(p.FullName));

File.WriteAllLines(outputFileName, allLines);

答案 2 :(得分:0)

试试这个:

var allLines = Directory.GetFiles(directory, "*.txt")
    .Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.Date)
    .SelectMany(f => File.ReadLines(f));