Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter files by creation date using c#

Tags:

c#

with the following code , I can merge text files which exist in a directory

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

How can I modify it to merge files which date creation is today ?

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

How can I combine the piece of code ?

like image 370
user3548593 Avatar asked Feb 13 '23 04:02

user3548593


2 Answers

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);
like image 127
Grant Winney Avatar answered Feb 24 '23 01:02

Grant Winney


Use File.GetCreationTime method:

var allLines = Directory.EnumerateFiles(directory, "*.txt", SearchOption.TopDirectoryOnly)
                        .Where(path => File.GetCreationTime(path).Date == DateTime.Today)
                        .SelectMany(f => File.ReadLines(f));
like image 29
Andrew Avatar answered Feb 24 '23 00:02

Andrew