简体   繁体   English

通过搜索条件检索文件列表的最快方法-C#

[英]Fastest way to retrieve list of files by search criteria - c#

I have a directory structure with txt files. 我有一个带有txt文件的目录结构。

I want to get a list of file names where the modified/creation date is between a range. 我想获取文件名列表,其中修改/创建日期在一个范围内。

So far, I have this: 到目前为止,我有这个:

        DirectoryInfo directory = new DirectoryInfo(@"C:\MotionWise\Manifest\000EC902F17F");
        DateTime from_date = DateTime.Now.AddMinutes(-300);
        DateTime to_date = DateTime.Now;
        List<FileInfo> files = directory.GetFiles("*", SearchOption.AllDirectories).Where(file => file.LastWriteTime >= from_date && file.LastWriteTime <= to_date).ToList();

Now,I am only interested in the full path name. 现在,我只对完整路径名感兴趣。

If I enumerate through the files list I can add the full path name to a new list/array etc. but this seems a waste of extra effort as I feel there is a way to do this in the lambada code? 如果我枚举文件列表,可以将完整路径名添加到新列表/数组等中,但这似乎浪费了额外的精力,因为我觉得可以在lambada代码中做到这一点?

If it can be done in the lambada code will not the selection by file info be too 'heavy'? 如果可以在lambada代码中完成,按文件信息进行的选择会不会太“繁重”? Is there a way to just select full path name without 'loading' each entry into a file info? 有没有一种方法可以只选择完整路径名,而无需将每个条目“加载”到文件信息中?

I have been toying with the idea of executing the dir DOS command and capturing the output in the Process class. 我一直在想执行dir DOS命令并在Process类中捕获输出。

If you're only interested in the paths don't use DirectoryInfo.GetFiles because it returns an array and because it is a FileInfo[] where each FileInfo object includes all informations that you're not interested in anyway. 如果仅对路径感兴趣,请不要使用DirectoryInfo.GetFiles因为它返回一个数组,并且因为它是FileInfo[] ,其中每个FileInfo对象都包含了您不感兴趣的所有信息。 You can use File.GetLastWriteTime to get it. 您可以使用File.GetLastWriteTime来获取它。

Instead use Directory.EnumerateFiles which lazily returns only paths that are matching your filter criteria and the search pattern. 而是使用Directory.EnumerateFiles ,它仅懒惰地返回与您的过滤条件和搜索模式匹配的路径。

List<string> paths = Directory.EnumerateFiles(@"C:\MotionWise\Manifest\000EC902F17F", "*", SearchOption.AllDirectories)
    .Where(path => {
        DateTime lastWriteTime = File.GetLastWriteTime(path);
        return lastWriteTime >= from_date && lastWriteTime <= to_date;
    })
    .ToList();

Just Select on the FullName : 只需在FullNameSelect

List<string> files = directory.GetFiles("*", SearchOption.AllDirectories)
                              .Where(file => file.LastWriteTime >= from_date && file.LastWriteTime <= to_date)
                              .Select(f => f.FullName)
                              .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM