5,530,111 members and growing! (16,231 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Directory Size

By Esben Sundgaard

An article on getting the size of all folders
C#, Windows, .NET, Visual Studio, Dev

Posted: 9 Apr 2006
Updated: 9 Apr 2006
Views: 27,488
Bookmarked: 20 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
10 votes for this Article.
Popularity: 3.17 Rating: 3.17 out of 5
2 votes, 20.0%
1
0 votes, 0.0%
2
3 votes, 30.0%
3
3 votes, 30.0%
4
2 votes, 20.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Sample Image - 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 for that job - and it was!
In very short time and very little code I made 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 said the code for this is really short. Especially with the .NET 2.0 version of GetDirectories which has and 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).
Also I have 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 the BackgroundWorker thread makes the program still responding while scanning and enables the user to cancel the operation.

The code that does the work:

private DataTable m_dirs = new DataTable(); 
private Dictionary<STRING double="">
</STRING> m_dirsSize = new Dictionary<STRING double="">
</STRING>();

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 finish 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 sum up in the DataTable but it is must faster using a generic Dictionary.

When the loop is finish 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 wants it to see 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 the GetFiles(). But to control which columns is showed 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Esben Sundgaard



Occupation: Web Developer
Location: Denmark Denmark

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 6 of 6 (Total in Forum: 6) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralWhere does it count size of files in root folder?memberPiotr Perak4:32 29 Jan '07  
GeneralRe: Where does it count size of files in root folder?memberB Parnell2:02 12 Jun '07  
GeneralESLmemberfwsouthern14:59 9 Apr '06  
GeneralRe: ESLmemberEsben Sundgaard0:00 10 Apr '06  
GeneralRe: ESLmembertkdmaster5:20 10 Apr '06  
GeneralRe: ESLmemberEsben Sundgaard5:27 10 Apr '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Apr 2006
Editor:
Copyright 2006 by Esben Sundgaard
Everything else Copyright © CodeProject, 1999-2008
Web19 | Advertise on the Code Project