Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleFind the total disk space used by a directory and its subdirectories
Keywordssize, disk space, directory, subdirectories
CategoriesFiles and Directories
 
Use the Dir command to search the directory hierarchy. Use FileLen to get the file sizes.
 
Private Sub Command1_Click()
Dim start_dir As String
Dim pattern As String
Dim file_list As String

    SizeLabel.Caption = ""
    ListText.Text = ""
    MousePointer = vbHourglass
    DoEvents
    
    start_dir = Trim$(StartText.Text)
    If Right$(start_dir, 1) = "\" Then _
        start_dir = _
            Left$(start_dir, Len(start_dir) - 1)
    pattern = Trim$(PatternText.Text)
    SizeLabel.Caption = Format$(ListFiles(start_dir, _
        pattern, file_list)) & " bytes"
    ListText.Text = file_list
    MousePointer = vbDefault
End Sub

' List all files below the directory that
' match the pattern.
Private Function ListFiles(ByVal start_dir As String, ByVal _
    pattern As String, file_list As String) As Double
Dim dir_names() As String
Dim num_dirs As Integer
Dim i As Integer
Dim fname As String
Dim full_name As String
Dim new_files As String
Dim attr As Integer
Dim total_size As Double

    ' Protects against such things as
    ' GetAttr("C:\pagefile.sys").
    On Error Resume Next
    
    ' Get the matching files in this directory.
    fname = Dir(start_dir & "\" & pattern, vbNormal)
    Do While fname <> ""
        full_name = start_dir & "\" & fname
        new_files = new_files & full_name & vbCrLf
        total_size = total_size + FileLen(full_name)
        fname = Dir()
    Loop
    file_list = file_list & new_files
    
    ' Optionally display the newlist here.
    
    ' Get the list of subdirectories.
    fname = Dir(start_dir & "\*.*", vbDirectory)
    Do While fname <> ""
        ' Skip this dir and its parent.
        attr = 0    ' In case there's an error.
        attr = GetAttr(start_dir & "\" & fname)
        If fname <> "." And fname <> ".." And _
            (attr And vbDirectory) <> 0 _
        Then
            num_dirs = num_dirs + 1
            ReDim Preserve dir_names(1 To num_dirs)
            dir_names(num_dirs) = fname
        End If
        fname = Dir()
    Loop
    
    ' Search the other directories.
    For i = 1 To num_dirs
        total_size = total_size + _
            ListFiles(start_dir & "\" & dir_names(i), _
                pattern, file_list)
    Next i

    ListFiles = total_size
End Function
 
Formatted by Neil Crosby
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated