简体   繁体   English

如何计算/确定 .NET 中的文件夹大小?

[英]How to calculate/determine Folder Size in .NET?

I am creating application in Winform which among other things will also need to have the ability to calculate size of the folder.我正在 Winform 中创建应用程序,其中还需要能够计算文件夹的大小。

Can someone give me pointers how to do that?有人可以给我指点如何做到这一点吗?

thanks谢谢

I use the following extension method to do that:我使用以下扩展方法来做到这一点:

    public static long Size(this DirectoryInfo Directory, bool Recursive = false)
    {
        if (Directory == null)
            throw new ArgumentNullException("Directory");
        return Directory.EnumerateFiles("*", Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Sum(x => x.Length);
    }

You will need to recursively enumerate the files in the folder and sum the file sizes.您将需要递归枚举文件夹中的文件并对文件大小求和。 Remember to include system and hidden files for the correct size.请记住包含正确大小的系统和隐藏文件。

Here is a simple version:这是一个简单的版本:

long GetFolderSize(string path)
{
    DirectoryInfo d = new DirectoryInfo(path);
    var files = d.GetFiles("*", SearchOption.AllDirectories);
    return files.Sum(fi => fi.Length);
}

Remember that a file may take up more space on the disk than it's Length, since a file always takes up a whole number of blocks on the file system (in case that matters to your application).请记住,文件在磁盘上占用的空间可能比它的长度更多,因为文件总是占用文件系统上的整数个块(如果这对您的应用程序很重要)。

You need to obtain all files from your directory (including subdirectories) and in the sum loop their size.您需要从您的目录(包括子目录)中获取所有文件,并在 sum 循环中获取它们的大小。 Example:例子:

static long GetDirectorySize(string path)
{
    string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

    long size = 0;
    foreach (string name in files)
    {
        FileInfo info = new FileInfo(name);
        size += info.Length;
    }

    return size;
}

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

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