How to get the Folder Size in VB.NET

My problem was not really big, but it was a problem which really irritated me a lot!!

We store data based on the user's alias in a folder called D:\SomeFolder on remote machine. In due course of time though, the hard disk starts giving No Disk Space problems, and we need to ask the users to delete the obsolete data. If they do it religiously, that's never a problem :o) So, all in all it is pretty time consuming to find out who is consuming the most amount of Disk Space. Here is what this utility does for me...

1. Prints the aliases of all the guys who are not freeing obsolete data in one line so that it is easy to send emails :o)
2. Prints the amount of space being consumed by that guy!

You can download the tool from this link.

Here is how the code is written for a file called FolderSize.vb. Just create a new Project and add a form called FolderSize. Go to the code view and paste the following... 

Imports System.IO
Public Class FolderSize
    Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        'This call is required by the Windows Form Designer.
        InitializeComponent()
        'Add any initialization after the InitializeComponent() call
    End Sub
    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer
    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer. 
    'Do not modify it using the code editor.
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents btnCalculate As System.Windows.Forms.Button
    Friend WithEvents btnBrowse As System.Windows.Forms.Button
    Friend WithEvents FolderBrowserDialog1 As System.Windows.Forms.FolderBrowserDialog
    Friend WithEvents txtLocation As System.Windows.Forms.TextBox
    Friend WithEvents txtOutput As System.Windows.Forms.TextBox
    Friend WithEvents Button1 As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.txtLocation = New System.Windows.Forms.TextBox
        Me.Label1 = New System.Windows.Forms.Label
        Me.txtOutput = New System.Windows.Forms.TextBox
        Me.btnCalculate = New System.Windows.Forms.Button
        Me.btnBrowse = New System.Windows.Forms.Button
        Me.FolderBrowserDialog1 = New System.Windows.Forms.FolderBrowserDialog
        Me.Button1 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'txtLocation
        '
        Me.txtLocation.Location = New System.Drawing.Point(80, 8)
        Me.txtLocation.Name = "txtLocation"
        Me.txtLocation.Size = New System.Drawing.Size(336, 20)
        Me.txtLocation.TabIndex = 1
        Me.txtLocation.Text = "D:\CaseFiles"
        '
        'Label1
        '
        Me.Label1.Location = New System.Drawing.Point(20, 12)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(60, 16)
        Me.Label1.TabIndex = 0
        Me.Label1.Text = "Location >"
        '
        'txtOutput
        '
        Me.txtOutput.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.txtOutput.Font = New System.Drawing.Font("Lucida Console", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txtOutput.Location = New System.Drawing.Point(0, 34)
        Me.txtOutput.Multiline = True
        Me.txtOutput.Name = "txtOutput"
        Me.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Both
        Me.txtOutput.Size = New System.Drawing.Size(780, 491)
        Me.txtOutput.TabIndex = 5
        Me.txtOutput.Text = ""
        '
        'btnCalculate
        '
        Me.btnCalculate.Location = New System.Drawing.Point(450, 8)
        Me.btnCalculate.Name = "btnCalculate"
        Me.btnCalculate.Size = New System.Drawing.Size(92, 20)
        Me.btnCalculate.TabIndex = 3
        Me.btnCalculate.Text = "&Calculate"
        '
        'btnBrowse
        '
        Me.btnBrowse.Location = New System.Drawing.Point(419, 8)
        Me.btnBrowse.Name = "btnBrowse"
        Me.btnBrowse.Size = New System.Drawing.Size(27, 20)
        Me.btnBrowse.TabIndex = 2
        Me.btnBrowse.Text = "..."
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(546, 8)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(92, 20)
        Me.Button1.TabIndex = 4
        Me.Button1.Text = "C&opy"
        '
        'FolderSize
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(780, 525)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.btnBrowse)
        Me.Controls.Add(Me.btnCalculate)
        Me.Controls.Add(Me.txtOutput)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.txtLocation)
        Me.Name = "FolderSize"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Folder Size"
        Me.ResumeLayout(False)
    End Sub
#End Region
    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        FolderBrowserDialog1.ShowDialog()
        txtLocation.Text = FolderBrowserDialog1.SelectedPath()
    End Sub
    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
        Dim objDir As DirectoryInfo = New DirectoryInfo(txtLocation.Text)
        Dim objFolder As DirectoryInfo
        Dim dblTotalSize As Double
        Dim objArray As New SortedList 'I am using the SortedList since I don't want to do the Sort operation myself.
        Dim i As Integer
        Dim strName As String
        Dim dblSize As Double
        Dim strToList As String
        Dim strCCList As String = "dsinettl"
        Try
            txtOutput.Text = String.Empty
            i = 0
            objArray.Clear()
            Me.Text = "Please wait..."
            'Reading each Folder's name and Size
            For Each objFolder In objDir.GetDirectories()
                dblTotalSize = GetFolderSize(objFolder.FullName, True) / (1024 * 1024)
                If Not dblTotalSize = 0 Then
                    objArray.Add(dblTotalSize, dblTotalSize.ToString & "\" & objFolder.Name)
                End If
                If dblTotalSize > 5000 Then
                    strToList += objFolder.Name + ";"
                End If
                Application.DoEvents()
            Next
            txtOutput.Text += strToList & vbCrLf & vbCrLf & strCCList & vbCrLf & vbCrLf
            'Creating the output now in reverse order since I want it to be sorted by Descending Order
            For i = objArray.Count - 1 To 0 Step -1
                strName = objArray.GetByIndex(i).ToString
                dblSize = strName.Substring(0, strName.IndexOf("\"))
                strName = strName.Substring(strName.IndexOf("\") + 1)
                txtOutput.Text += strName & Space(50 - strName.Length) & _
                String.Format("{0, 10}", FormatNumber(dblSize, 2)) & " MB" & vbCrLf
            Next
            Me.Text = "Folder Size - Done!"
        Catch Ex As Exception
            MsgBox(Ex.Message)
        End Try
    End Sub
    'This is a recursive function which calculates the Folder Size
    Function GetFolderSize(ByVal DirPath As String, Optional ByVal IncludeSubFolders As Boolean = True) As Long
        Dim lngFolderSize As Long
        Dim objFileInfo As FileInfo
        Dim objFolder As DirectoryInfo
        Dim objSubFolder As DirectoryInfo
        Try
            objFolder = New DirectoryInfo(DirPath)
            For Each objFileInfo In objFolder.GetFiles()
                lngFolderSize += objFileInfo.Length
            Next
            If IncludeSubFolders Then
                For Each objSubFolder In objFolder.GetDirectories()
                    lngFolderSize += GetFolderSize(objSubFolder.FullName)
                Next
            End If
        Catch Ex As Exception
            MsgBox(Ex.Message)
        End Try
        Return lngFolderSize
    End Function
    'Setting the data in txtOutput to the Clipboard
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Clipboard.SetDataObject(txtOutput.Text.ToString)
    End Sub
End Class

Execute the code and you should be good to go. Modify it according to your requirements :o)

Cheers,
Rahul

kick it on DotNetKicks.com

Share this post : email it! | bookmark it! | digg it! | reddit! | kick it! | live it!