得到目录大小的更有效的方法 [英] More efficient method of getting Directory size

查看:134
本文介绍了得到目录大小的更有效的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立一个递归函数来得到一个文件夹路径的目录大小。然而,它的工作原理,与不断增长数量的目录我要通过搜索(以及在每个相应的文件夹的文件的数目),这是一个非常缓慢的,低效率的方法。

I've already build a recursive function to get the directory size of a folder path. It works, however with the growing number of directories I have to search through (and number of files in each respective folder), this is a very slow, inefficient method.

static string GetDirectorySize(string parentDir)
{
    long totalFileSize = 0;

    string[] dirFiles = Directory.GetFiles(parentDir, "*.*", 
                            System.IO.SearchOption.AllDirectories);

    foreach (string fileName in dirFiles)
    {
        // Use FileInfo to get length of each file.
        FileInfo info = new FileInfo(fileName);
        totalFileSize = totalFileSize + info.Length;
    }
    return String.Format(new FileSizeFormatProvider(), "{0:fs}", totalFileSize);
}

这是搜索所有子目录的说法路径,因此 dirFiles 阵列变得相当大。有没有更好的方法来做到这一点?我四处搜查,但没有发现任何东西。

This is searches all subdirectories for the argument path, so the dirFiles array gets quite large. Is there a better method to accomplish this? I've searched around but haven't found anything yet.

另一个想法掠过我脑海里把结果在缓存中,当函数再次被调用,尝试并发现已更改的分歧,只能重新搜索文件夹。不知道这是一件好事,要么...

Another idea that crossed my mind was putting the results in a cache and when the function is called again, try and find the differences and only re-search folders that have changed. Not sure if that's a good thing either...

推荐答案

您先扫描树来获取所有文件的列表。那么你重新打开每个文件来获得它的大小。这相当于扫描两次。

You are first scanning the tree to get a list of all files. Then you are reopening every file to get its size. This amounts to scanning twice.

我建议你使用DirectoryInfo.GetFiles将交给你了FileInfo对象直接。这些对象预填充其长度。

I suggest you use DirectoryInfo.GetFiles which will hand you FileInfo objects directly. These objects are pre-filled with their length.

在.NET 4中,您还可以使用EnumerateFiles方法,该方法将返回一个懒惰IEnumable。

In .NET 4 you can also use the EnumerateFiles method which will return you a lazy IEnumable.

这篇关于得到目录大小的更有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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