开发者

How to calculate/determine Folder Size in .NET?

开发者 https://www.devze.com 2023-03-28 17:42 出处:网络
I am creating application in Winform which among other things will also need to have the ability to calculate size of the folder.

I am creating application in Winform which among other things will also need to have the ability to calculate size of the folder.

Can someone give me pointers how to do that?

thanks开发者_Go百科


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. 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消