How do I Get Folder Size in C#? [duplicate]

走远了吗. 提交于 2020-01-01 11:23:51

问题


Possible Duplicate:
How do I get a directory size (files in the directory) in C#?

In vbscript, it's incredibly simple to get the folder size in GB or MB:

Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim fSize = CInt((oFSO.GetFolder(path).Size / 1024) / 1024)
WScript.Echo fSize

In C#, with all my searches, all I can come up with are long, convoluted, recursive searches for every file size in all subfolders, then add them all up at the end.

Is there no other way?


回答1:


How about this:

private static long GetDirectorySize(string folderPath)
{
    DirectoryInfo di = new DirectoryInfo(folderPath);
    return di.EnumerateFiles("*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}

from here.

This will give you the size in bytes; you will have to "prettify" that into GBs or MBs.

NOTE: This only works in .NET 4+.

EDIT: Changed the wildcard search from "*.*" to "*" as per the comments in the thread to which I linked. This should extend its usability to other OSes (if using Mono, for example).




回答2:


You can also use recursion to get all subdirectories and sum the sizes:

public static long GetDirectorySize(string path){
    string[] files = Directory.GetFiles(path);
    string[] subdirectories = Directory.GetDirectories(path);

    long size = files.Sum(x => new FileInfo(x).Length);
    foreach(string s in subdirectories)  
        size += GetDirectorySize(s);

    return size;
}


来源:https://stackoverflow.com/questions/12166404/how-do-i-get-folder-size-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!