C#中主文件夹和子文件夹中磁盘上文件夹的大小。帮助子文件夹

时间:2016-02-23 22:41:14

标签: c# .net collections ienumerable directoryinfo

我是C#世界的新手,我正在尝试获取目录/文件夹的dis大小。下面是文件夹和子文件夹总大小的代码。我想要这个总大小,但我想要的更多是为目录中的其他子文件夹获得相同的结果。例如:主目录/文件夹是Fruit,它有子文件夹名为Orange,Apple,Mango等。所以这个代码获得了Fruit的总大小,但现在我想要单独列出Orange,Apple,Mango的总大小。

请帮我修复代码!

class Program
{
    static void Main(string[] args)
    {
        DirectoryInfo dInfo = new DirectoryInfo(@"C:\Users");

        long sizeOfDir = DiskSize(dInfo, true);

        Console.WriteLine("Size on disk in MB : " +
        "{0:N2} MB", ((double)sizeOfDir) / (1024 * 1024));

        Console.ReadLine();
    }

    static long DiskSize(DirectoryInfo dInfo, bool includeSubDir)
    {

        long totalSize = dInfo.EnumerateFiles()
                     .Sum(file => file.Length);


        if (includeSubDir)
        {

            totalSize += dInfo.EnumerateDirectories()
                     .Sum(dir => DiskSize(dir, true));
        }
        return totalSize;
    }

3 个答案:

答案 0 :(得分:0)

如何做到以下几点?

var files = Directory.GetFiles(@"C:\Users", "*.*", SearchOption.AllDirectories);

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

答案 1 :(得分:0)

您可以使用GetDirectories()方法,并递归调用函数,在每个DirectoryInfo对象的磁盘上获取大小。

    static void Main(string[] args)
    {
        ScanDisksForSize(new DirectoryInfo(@"C:\Users"));
        Console.ReadLine();
    }

    static void ScanDirectoriesForSize(DirectoryInfo topDir)
    {
        long sizeOfDir;
        if (topDir != null)
            sizeOfDir = DiskSize(topDir);
        else
            return;
        Console.WriteLine("Size on disk of {0}: {1:N2} MB", topDir.Name, ((double)sizeOfDir) / (1024 * 1024));

        //Do subfolders

        var subFolders = topDir.GetDirectories();
        if (subFolders == null)
            return;
        foreach (var folder in subFolders)
            ScanDisksForSize(folder);
    }

    static long DiskSize(DirectoryInfo dInfo)
    {
        try
        {   
            long totalSize = dInfo.EnumerateFiles().Sum(file => file.Length);
        return totalSize;
        }
        catch (Exception)
        {
            return 0;
        }
    }

不要包含一些错误检查。

答案 2 :(得分:0)

这是我测试过的代码。为每个目录提供结果。

class Program {
    static void Main(string[] args) {
      DirectoryInfo dInfo = new DirectoryInfo(@"D:\temp");

      foreach (DirectoryInfo item in dInfo.EnumerateDirectories()) {

        long sizeOfDir = DiskSize(item, true);


      Console.WriteLine("Size on disk in MB : " +
      "{0:N2} MB", ((double)sizeOfDir) / (1024 * 1024));


      }
      Console.ReadLine();
    }

    static long DiskSize(DirectoryInfo dInfo, bool includeSubDir) {

      long totalSize = dInfo.EnumerateFiles()
                   .Sum(file => file.Length);


      if (includeSubDir) {

        totalSize += dInfo.EnumerateDirectories()
                 .Sum(dir => DiskSize(dir, true));
      }
      return totalSize;
    }
  }