Calculate Directory Size

In this chapter you will learn:

  1. Calculate Directory Size

Calculate Directory Size

using System;/*from  j  ava  2  s  . c  om*/
using System.IO;

static class MainClass
{
    static void Main(string[] args)
    {
        DirectoryInfo dir = new DirectoryInfo("c:\\a");
        Console.WriteLine("Total size: " + CalculateDirectorySize(dir, true).ToString() + " bytes.");

    }

    static long CalculateDirectorySize(DirectoryInfo directory, bool includeSubdirectories)
    {
        long totalSize = 0;

        // Examine all contained files.
        FileInfo[] files = directory.GetFiles();
        foreach (FileInfo file in files)
        {
            totalSize += file.Length;
        }

        // Examine all contained directories.
        if (includeSubdirectories)
        {
            DirectoryInfo[] dirs = directory.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
            {
                totalSize += CalculateDirectorySize(dir, true);
            }
        }

        return totalSize;
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Get a list of invalid path characters
Home » C# Tutorial » File, Path
File creation
Deleting Files
Put to recycle bin
File Exists
File moving
File size
File attribute
Set file attribute
File time change
File time
Random file name
Temporary file
Path
Directory creation
Delete directory
Path existance
Change the path
Current Path
Directory listing
Recursive Path Listing
Combine path
Calculate Directory Size
Invalid path characters
System path
Directory copy
Drive
Drive information
File access rule
File System watcher