Click here to Skip to main content
Click here to Skip to main content

Directory Size

, 9 Apr 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
An article on getting the size of all folders
DirectorySize_preview.JPG

Introduction

I needed a program that could help me clean up my old PC. Therefore I wanted a program that could show the size of each folder. My first thought was that .NET 2.0 (C#) was the perfect solution for that job - and it was!

In a very short time and with very little code, I wrote a program that listed all folders from a selected folder (or a complete hard drive) with the size (and accumulated size) of each folder.

Using the Code

As I mentioned earlier, the code for this is really short. Especially with the .NET 2.0 version of GetDirectories which has an option for searching all subdirectories, this was a very easy job.

In the application, I have a region for the Form. This is only for improving the user interface (saving the form size and position on close and setting the gridview size when the form is resized).

I have also made the program run as a BackgroundWorker thread. This is also not necessary but it gives a better user experience, especially if the user wants to scan the complete hard drive. In this case, the BackgroundWorker thread keeps the program still responding while scanning and enables the user to cancel the operation.

The code that does the work is given below:

private DataTable m_dirs = new DataTable(); 
private Dictionary m_dirsSize = new Dictionary();

private bool LoopFolder(DirectoryInfo root) 
{ 
    if (this.backgroundWorker1.CancellationPending) 
        return false; 
    
    foreach (DirectoryInfo di in root.GetDirectories("*", SearchOption.AllDirectories)) 
    { 
        string fullname = di.FullName; 
        
        SetStatusBar(fullname); 
        
        double size = GetFilesSize(di); 
        
        DataRow dr = m_dirs.NewRow(); 
        
        dr["Name"] = fullname; 
        dr["Size"] = size; 

        m_dirs.Rows.Add(dr); 
        m_dirsSize.Add(fullname, size); 

        // sum up the fullsize on all parents 
        DirectoryInfo parent = di.Parent; 
        while (parent != null && !this.backgroundWorker1.CancellationPending) 
        { 
            if (m_dirsSize.ContainsKey(parent.FullName)) 
            { 
                m_dirsSize[parent.FullName] += size; 
                parent = parent.Parent; 
            } 
            else 
                break; 
        } 
    } 
    
    return true; 
}

The program loops all directories and adds them to a DataTable. When finished, the DataTable can then be bound to the gridview. The program uses a generic Dictionary to sum up the size of each parent. This could also have been summed up in the DataTable but it is must faster using a generic Dictionary.

When the loop is finished, the program runs through every DataRow in the DataTable to round the size and to insert the accumulated size in the DataTable:

foreach (DataRow dr in m_dirs.Rows) 
{ 
    dr["Size"] = Math.Round((double)dr["Size"], 2); 
    
    string fullname = (string)dr["Name"]; 
    
    if (m_dirsSize.ContainsKey(fullname)) 
        dr["Fullsize"] = Math.Round(m_dirsSize[fullname], 2); 
} 

One last thing that we usually also want to see is the size of each file in a folder.
This is done in the SelectionChanged event of the gridview:

if (grdDirectories.SelectedRows.Count == 1) 
{ 
    string directory = grdDirectories.SelectedRows[0].Cells[0].Value.ToString(); 
    
    toolStripStatusLabel1.Text = directory; 

    DataTable tblFiles = new DataTable(); 
    
    tblFiles.Columns.Add("Name", typeof(string)); 
    tblFiles.Columns.Add("Size", typeof(double)); 
    tblFiles.Columns.Add("LastAccessTime", typeof(DateTime)); 
    tblFiles.Columns.Add("LastWriteTime", typeof(string)); 
    tblFiles.Columns.Add("CreationTime", typeof(string)); 
    tblFiles.Columns.Add("ReadOnly", typeof(bool)).ReadOnly = true; 
    tblFiles.Columns.Add("Ext", typeof(string)); 

    DirectoryInfo di = new DirectoryInfo(directory); 

    foreach (FileInfo fi in di.GetFiles()) 
    { 
        DataRow dr = tblFiles.NewRow(); 

        dr["Name"] = fi.Name; 
        dr["LastAccessTime"] = fi.LastAccessTime; 
        dr["Size"] = Math.Round(fi.Length / 1024.0 / 1024.0, 2); // size in MB 
        dr["LastWriteTime"] = fi.LastWriteTime; 
        dr["ReadOnly"] = fi.IsReadOnly; 
        dr["CreationTime"] = fi.CreationTime; 
        dr["Ext"] = fi.Extension; 
        
        tblFiles.Rows.Add(dr); 
    } 
    
    tblFiles.DefaultView.Sort = "Size desc"; 
    
    grdFiles.DataSource = tblFiles; 
}

You can actually bind the gridview directly to the FileInfo[] from GetFiles(). But to control which columns are shown, I use a DataTable. Using a DataTable also makes it possible to sort gridview.

Points of Interest

One thing that would be nice to add is the opportunity to delete a folder or file.

History

  • 9th April, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Esben Sundgaard
Web Developer
Denmark Denmark
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberbouleanu10-Aug-10 22:50 
QuestionWhere does it count size of files in root folder? PinmemberPiotr Perak29-Jan-07 4:32 
AnswerRe: Where does it count size of files in root folder? PinmemberB Parnell12-Jun-07 2:02 
GeneralESL Pinmemberfwsouthern9-Apr-06 14:59 
Please run spell check, particularly on your article title ..... preferably prior to posting.
GeneralRe: ESL PinmemberEsben Sundgaard10-Apr-06 0:00 
GeneralRe: ESL Pinmembertkdmaster10-Apr-06 5:20 
GeneralRe: ESL PinmemberEsben Sundgaard10-Apr-06 5:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 9 Apr 2006
Article Copyright 2006 by Esben Sundgaard
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid