Kuttan Sujith
Kuttan Sujith

Reputation: 7979

Linq to file system to get last created file in each sub folders

I have a folder/directory that contains some sub directories.

Only those sub folders contain files. I have to get the full path of last created files in each sub folder.

Only the last created file in each sub folder is needed.

How can I do this? How can I use linq to files stem for this

Upvotes: 1

Views: 650

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160882

Something like this would work:

DirectoryInfo di = new DirectoryInfo(@"C:\SomeFolder");

var recentFiles = di.GetDirectories()
                    .Select(x=>x.EnumerateFiles()
                                .OrderByDescending(f=> f.CreationTimeUtc)
                                .FirstOrDefault())
                    .Where(x=> x!=null)
                    .Select(x=>x.FullName)
                    .ToList();

One thing to be mindful of is the permissions you need to traverse some protected directories, this shouldn't be a problem for most cases though.

Upvotes: 7

Related Questions