C#: Calculate the size of a Directory

You need to calculate the size of all files contained  in a directory.
The code:
The DirectoryInfo class does not provide any property that returns size information. However, you can easily calculate the size of all files contained in a directory using the FileInfo.Length property.

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
    class Program
        static void Main(string[] args)
            if (args.Length == 0)
                Console.WriteLine("Please supply a directory path.");
            DirectoryInfo dir = new DirectoryInfo(args[0]);
            long DirSize = long.Parse(CalculateDirectorySize(dir, true).ToString());
            DirSize = DirSize / 1024;
            Console.WriteLine("Total size: " + DirSize + "Kbytes.");
            Console.WriteLine("Main method complete. Press Enter");
        static long CalculateDirectorySize(DirectoryInfo directory, bool includeSubdirectories)
            long totalsize = 0;
            FileInfo[] files = directory.GetFiles();
            foreach (FileInfo file in files)
                totalsize += file.Length;
            if (includeSubdirectories)
                DirectoryInfo[] dirs = directory.GetDirectories();
                foreach (DirectoryInfo dir in dirs)
                    totalsize += CalculateDirectorySize(dir, true);
            return totalsize;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s