包含子文件夹的文件总大小

时间:2014-09-01 12:32:22

标签: c# file size

迭代文件夹和子文件夹以获取从指定位置开始的每个文件夹的总大小的最佳方法是什么?

小样本:

C:/,d:/,F:/游戏,G:/ BLA / BLA / BLA,

我想要一个检查根目录大小的方法。 所以像这样:

C:/ totalsize = 1000GB,D:/总大小= 1000GB,F:/游戏总大小为F:/ = 1000GB,G:/ bla / bla / bla,总大小为G:/ = 1000GB

foreach (string directory in drives)
        {
            if (directory == GoPro1 || directory == GoPro2 || directory == GoPro3 || directory == GoPro4)
            {
                //gets drive letter from directory location
                var drive = Path.GetPathRoot(directory);

                //create new drive info
                DriveInfo di = new DriveInfo(drive);

                verbruik[teller1] = ("Total Size " + di.TotalSize / 1024 / 1024 / 1024 + " GB " + "Free Space " + di.AvailableFreeSpace / 1024 / 1024 / 1024 + "GB" + "       Total Sub dir: " + drive);
                teller1 = teller1 + 1;
            }

        }

这就是我所拥有的,但这不会显示所选子文件夹的总大小。

1 个答案:

答案 0 :(得分:1)

public static long GetFolderSize(string directory)
{
    return new DirectoryInfo(directory).GetFiles("*.*", SearchOption.AllDirectories).Sum(file => file.Length);
}