Linq to file system to get last created file in ea

2019-03-01 23:12发布

问题:

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

回答1:

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.