完善列举使用.NET文件和文件夹的性能 [英] Improve the performance for enumerating files and folders using .NET

查看:110
本文介绍了完善列举使用.NET文件和文件夹的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几千个文件夹,一个基本目录。内这些文件夹可以有1到20之间的子文件夹,包含1和10之间的文件。我想删除超过60天的所有文件。我用下面的code得到的文件列表中,我将不得不删除:

I have a base directory that contains several thousand folders. Inside of these folders there can be between 1 and 20 subfolders that contains between 1 and 10 files. I'd like to delete all files that are over 60 days old. I was using the code below to get the list of files that I would have to delete:

DirectoryInfo dirInfo = new DirectoryInfo(myBaseDirectory);
FileInfo[] oldFiles = 
  dirInfo.GetFiles("*.*", SearchOption.AllDirectories)
    .Where(t=>t.CreationTime < DateTime.Now.AddDays(-60)).ToArray();

不过,我让这个经营了约30分钟,但仍没有完成。我很好奇,如果任何人都可以看到反正,我可以潜在地改善上述线路的性能,或者如果有不同的方式,我应该完全处理这个获得更好的性能?建议?

But I let this run for about 30 minutes and it still hasn't finished. I'm curious if anyone can see anyway that I could potentially improve the performance of the above line or if there is a different way I should be approaching this entirely for better performance? Suggestions?

推荐答案

这是(可能是)好,因为它会得到:

This is (probably) as good as it's going to get:

DateTime sixtyLess = DateTime.Now.AddDays(-60);
DirectoryInfo dirInfo = new DirectoryInfo(myBaseDirectory);
FileInfo[] oldFiles = 
    dirInfo.EnumerateFiles("*.*", SearchOption.AllDirectories)
           .AsParallel()
           .Where(fi => fi.CreationTime < sixtyLess).ToArray();

更改:

  • 提出的60日少的DateTime 不变,因此更少的CPU负荷。
  • 使用 EnumerateFiles
  • 查询制并行。
  • Made the the 60 days less DateTime constant, and therefore less CPU load.
  • Used EnumerateFiles.
  • Made the query parallel.

如果在一个较小的时间运行(不知道如何小得多)。

Should run in a smaller amount of time (not sure how much smaller).

下面是可能比第一更快或更慢的另一解决方案,它取决于数据:

Here is another solution which might be faster or slower than the first, it depends on the data:

DateTime sixtyLess = DateTime.Now.AddDays(-60);
DirectoryInfo dirInfo = new DirectoryInfo(myBaseDirectory);
FileInfo[] oldFiles = 
     dirInfo.EnumerateDirectories()
            .AsParallel()
            .SelectMany(di => di.EnumerateFiles("*.*", SearchOption.AllDirectories)
                                .Where(fi => fi.CreationTime < sixtyLess))
            .ToArray();

这移动并行的主文件夹枚举。大多数从上面的变化施加太大。

Here it moves the parallelism to the main folder enumeration. Most of the changes from above apply too.

这篇关于完善列举使用.NET文件和文件夹的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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