Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order (and enumerate) directory listing by file creation date?

Tags:

c#

linq

So I have this routine:

public static IEnumerable<string> GetFiles( string path, string[] searchPatterns, SearchOption searchOption = SearchOption.TopDirectoryOnly) {
    return searchPatterns.AsParallel()
                         .SelectMany(searchPattern => 
                             Directory.EnumerateFiles(path, searchPattern, searchOption))
                         .OrderBy<string, string>( (f) => f)
                         .Distinct<string>();
}

and its working but ordering the files by its name and I need to order the files returned by its creation date. How can I sort by that if the item is an string like in the routine. I want to use Enumerate cause files are expected to be more than 1k.

Thanks.

like image 736
Erre Efe Avatar asked Jun 09 '12 22:06

Erre Efe


2 Answers

I'm not sure you really want to be using the Task Parallel Library for that query. For some reasons, see this question How to find all exe files on disk using C#?.

As for enumerating the files by creation date, I would start the function by creating a new DirectoryInfo using the path provided, and then call .EnumerateFiles(string pattern, SearchOption searchOption) to get all the files matching your pattern. Finally, you can order by the CreationTime property of the FileInfo objects in the returned enumeration and then either return the full FileInfo objects, or just their Name, like so:

public static IEnumerable<string> GetFiles( string path, string[] searchPatterns, SearchOption searchOption = SearchOption.TopDirectoryOnly) {
    DirectoryInfo dir = new DirectoryInfo(path);
    var dirs = (from file in dir.EnumerateFiles(searchPatterns, searchOptions)
            orderby file.CreationTime ascending
            select file.Name).Distinct(); // Don't need <string> here, since it's implied
    return dirs;
}

Note: I don't have access to a compiler at the moment, but I believe the above code is error free.

like image 172
Jon Senchyna Avatar answered Oct 21 '22 22:10

Jon Senchyna


You need to switch to using DirectoryInfo.EnumerateFiles, which will return a collection of FileInfo instances. You can then sort these by dates and select out the names.

like image 38
Reed Copsey Avatar answered Oct 21 '22 23:10

Reed Copsey