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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With