Build folder explorer with c# .Net

By , last updated February 9, 2016

Windows systems don’t show folder sizes per default. One need to either use a third party software or make a script or a program yourself. In this tutorial I will show how to create a simple C# application in Visual Studio that shows folder sizes on your Windows machine.

Create C# .NET project

I’m going to use Visual Studio 2013 and create a simple Forms application:

create new windows forms application in visual studio c sharp form 2013

In the Form Designer we create two text boxes and a button “Choose”:

visual studio c sharp form to choose folder size

We make the simplest application that will bring up the folder browsing dialog when the user clicks the button “Choose”. After the user chooses the folder it will appear in the second text box and show the size of this folder.

Choosing the Folder

In order to choose the folder in the file browsing dialog we can use the FolderBrowserDialog class in C#.

Create an event for the “Choose” button by clicking on it in the Form Designer. Fill in the function with the code to choose the folder and show the results in the text box:

private void button1_Click(object sender, EventArgs e)
{
	var dialog = new System.Windows.Forms.FolderBrowserDialog();
	DialogResult result = dialog.ShowDialog();
	if (result == DialogResult.OK)
	{
		textBox1.Text = dialog.SelectedPath;
		printFolderSize(dialog.SelectedPath);           
	}
}

We didn’t give any new names to the Form items for the purposes of this tutorial:

  • textBox1 – the smallest text box at the top of the form. It will show what folder the user has chosen.
  • richTextBox1 – the biggest textarea where the result of the size calculation will appear.
  • button1 – the “Choose” button.

Calculate Folder size

Create a function called printFolderSize with a string as an input. Test it by printing the chosen folder:

private void printFolderSize(string folder)
{            
	richTextBox1.AppendText(folder);
	richTextBox1.AppendText("n");
}

In order to calculate the size of the folder we need:

  • Calculate how much space each file within the folder take.
  • Accumulate all files from all the folders within the chosen folder together.

Recursive function is a good solution in this case. Recursive function is a function that calls itself. It is also called a direct recursion. One should be careful to use these functions as they can create endless loops within the application.

To find how much space a single file takes we use the FileInfo class in C#:

FileInfo[] files = directoryInfo.GetFiles();
foreach (FileInfo file in files)
{
	size += file.Length;
}

To explore all the folders in a directory, we use the DirectoryInfo class in C#. Create a new function getDirSize with DirectoryInfo as an input. The function will look like this:

private static long getDirSize(DirectoryInfo d)
{
	long size = 0;
   
	FileInfo[] files = d.GetFiles();
	foreach (FileInfo file in files)
	{
		size += file.Length;
	}
	

	DirectoryInfo[] directories = d.GetDirectories();
	foreach (DirectoryInfo dir in directories)
	{
		size += getDirSize(dir);
	}
	return size;
}

Convert results

The calculated folder size is a long value and shows how much space the folder takes in bytes. If we print the result at this stage we will get something like this:

folder size windows bytes c sharp program

The number 1148966285 bytes is not the same as 1,1 GB. Remember, that there are 1024 bytes in one KB.

This is how many bytes it is in a kilobyte, megabyte, gigabyte and so on:

  • A Kilobyte (KB) is 1,024 bytes.
  • A Megabyte (MB) is 1,048,576 bytes or 1,024 Kilobytes.
  • A Gigabyte (GB) is 1,073,741,824 bytes or 1,024 Megabytes or 1,048,576 Kilobytes.
  • A Terabyte (TB) is 1,099,511,627,776 bytes or 1,024 Gigabytes or 1,048,576 Megabytes or 1,073,741,824 kilobytes.
  • A Petabyte (PB) is 1,125,899,906,842,624 bytes.
  • An Exabyte (EB) is 1,152,921,504,606,846,976 bytes.
  • A Zettabyte (ZB) is 1,180,591,620,717,411,303,424 bytes.
  • A Yottabyte (YB) is 1,208,925,819,614,629,174,706,176 bytes.

For the purpose of this tutorial we write a simple conversion:

if(bytes_size > 1073741824) 
{
	richTextBox1.AppendText("" + bytes_size / 1073741824 + " GB   ");
} 
else if (bytes_size > 1048576)
{
	richTextBox1.AppendText("" + bytes_size / 1048576 + " MB   ");
}
else if (bytes_size > 1024)
{
	richTextBox1.AppendText("" + bytes_size / 1024 + " KB   ");
}
else
{
	richTextBox1.AppendText("" + bytes_size + " B   ");
}

Now the result is easy to read:

folder size in gigabytes c sharp tutorial visual studio

Exceptions

The code in this tutorial is not “bullet proof”. For example, when I have chosen the folder that contained files with restricted access, an exception was thrown:

denied access exception visual studio c sharp folder size program

Visual Studio Debugger tells us that the exception appeared while trying to access files from a chosen directory. An exception handling should be implemented.

exception handling debug folder size application c sharp visual studio

As we see our program won’t give an absolutely accurate result for how much space a folder takes as it won’t have access to the restricted files.

Final code

The whole code for this tutorial is simple. It can be used to build up the application for your own needs.

using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace DirectorySize
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                textBox1.Text = dialog.SelectedPath;
                printFolderSize(dialog.SelectedPath);           
            }
        }

        private void printFolderSize(string folder)
        {
            long bytes_size = getDirSize(new DirectoryInfo(folder));

            if(bytes_size > 1073741824) 
            {
                richTextBox1.AppendText("" + bytes_size / 1073741824 + " GB   ");
            } 
            else if (bytes_size > 1048576)
            {
                richTextBox1.AppendText("" + bytes_size / 1048576 + " MB   ");
            }
            else if (bytes_size > 1024)
            {
                richTextBox1.AppendText("" + bytes_size / 1024 + " KB   ");
            }
            else
            {
                richTextBox1.AppendText("" + bytes_size + " B   ");
            }
            
            richTextBox1.AppendText(folder);
            richTextBox1.AppendText("n");
        }

        private static long getDirSize(DirectoryInfo d)
        {
            long size = 0;
           
            FileInfo[] files = d.GetFiles();
            foreach (FileInfo file in files)
            {
                size += file.Length;
            }
            

            DirectoryInfo[] directories = d.GetDirectories();
            foreach (DirectoryInfo dir in directories)
            {
                size += getDirSize(dir);
            }
            return size;
        }
    }
}

Senior Software Engineer developing all kinds of stuff.

Comments

Be the first to comment.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*