2014年11月17日 星期一

計算目錄大小及檔案數量

1.使用.Net Framework 4.5
2.using System.IO
3.計算目錄大小:
static long CalculateDirectorySize(DirectoryInfo directory, bool includeSubdirectories)
{
    long totalSize = directory.EnumerateFiles().Sum(file => file.Length);
    if (includeSubdirectories)
    {
         totalSize += directory.EnumerateDirectories().Sum(dir => CalculateDirectorySize(dir, true));
     }
     return totalSize
}
4.計算被指定目錄的檔案數量(含子目錄)
static string CalculateDirectoryFiles(string directory)
{
    string fileCount = null;

    DirectoryInfo dir = new DirectoryInfo(directory);
    int files = dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Count();
    fileCount = files.ToString("#,0");
     return fileCount;
    }

沒有留言: