Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#
Article

Directory Size

Rate me:
Please Sign up or sign in to vote.
3.65/5 (13 votes)
9 Apr 2006CPOL2 min read 65.1K   1.2K   32   7
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:

C#
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:

C#
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:

C#
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)


Written By
Web Developer
Denmark Denmark
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
bouleanu10-Aug-10 21:50
bouleanu10-Aug-10 21:50 
QuestionWhere does it count size of files in root folder? Pin
Piotr Perak29-Jan-07 3:32
Piotr Perak29-Jan-07 3:32 
AnswerRe: Where does it count size of files in root folder? Pin
B Parnell12-Jun-07 1:02
B Parnell12-Jun-07 1:02 
GeneralESL Pin
fwsouthern9-Apr-06 13:59
fwsouthern9-Apr-06 13:59 
GeneralRe: ESL Pin
Esben Sundgaard9-Apr-06 23:00
Esben Sundgaard9-Apr-06 23:00 
GeneralRe: ESL Pin
tkdmaster10-Apr-06 4:20
tkdmaster10-Apr-06 4:20 
GeneralRe: ESL Pin
Esben Sundgaard10-Apr-06 4:27
Esben Sundgaard10-Apr-06 4:27 

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

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