按文件创建日期排序(并枚举)目录列表? [英] Order (and enumerate) directory listing by file creation date?

查看:69
本文介绍了按文件创建日期排序(并枚举)目录列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个例程:

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>();
}

及其工作但按其名称排序文件,我需要对按其创建日期返回的文件进行排序.如果项目是例行程序中的字符串,我该如何排序.我想使用枚举原因文件,预计超过1k.

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.

谢谢.

推荐答案

我不确定您是否真的想针对该查询使用任务并行库.出于某些原因,请参阅此问题如何查找所有exe使用C#在磁盘上保存文件?.

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#?.

关于按创建日期枚举文件,我将通过创建一个新的 DirectoryInfo 使用提供的路径,然后调用 CreationTime 进行订购.返回的枚举中 FileInfo 对象的属性,然后返回完整的FileInfo对象,或者仅返回其名称,就像这样:

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.

这篇关于按文件创建日期排序(并枚举)目录列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆