Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How To Find The Size Of A Folder and All Its SubFolders

Folders and Files

How To Find The Size Of A Folder and All Its SubFolders

by  mmilan  Posted    (Edited  )
Bit of code for anyone who wants it - I wrote this for finding the size of a folder and all it's subfolders.

Code:
Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
Private Type FILETIME
        dwLowDateTime As Long
        dwHighDateTime As Long
End Type
Private Type WIN32_FIND_DATA
        dwFileAttributes As Long
        ftCreationTime As FILETIME
        ftLastAccessTime As FILETIME
        ftLastWriteTime As FILETIME
        nFileSizeHigh As Long
        nFileSizeLow As Long
        dwReserved0 As Long
        dwReserved1 As Long
        cFileName As String * 255
        cAlternate As String * 14
End Type
Private Const INVALID_HANDLE_VALUE = -1
Private Const FILE_ATTRIBUTE_DIRECTORY = &H10
Private Const ERROR_NO_MORE_FILES = 18&

Private Function FolderSize(sFolder) As Double
  
  Dim FindInfo As WIN32_FIND_DATA
  Dim lFindHandle As Long
  Dim lTemp As Long
  Dim dSize As Double
  Dim bNextLoop As Boolean
  Dim sFileName As String
  
  
  'Open up an API FIND on the folder.
  lFindHandle = FindFirstFile(sFolder + "\*", FindInfo)
  If lFindHandle <> INVALID_HANDLE_VALUE Then
    
    Do
      sFileName = FindInfo.cFileName
      sFileName = Replace(sFileName, Chr(0), " ")
      sFileName = Trim(sFileName)
      
      If sFileName <> "." And sFileName <> ".." Then
      
        If (FindInfo.dwFileAttributes And FILE_ATTRIBUTE_DIRECTORY) = FILE_ATTRIBUTE_DIRECTORY Then
          'We're on a folder.
          dSize = dSize + FolderSize(sFolder + "\" + sFileName)
        Else
          'We're on a file.
          dSize = dSize + FindInfo.nFileSizeLow
          dSize = dSize + (FindInfo.nFileSizeHigh * (2 ^ 16))
        End If
        
      End If
      
      FindInfo.cFileName = String(255, vbNullChar)
      lTemp = FindNextFile(lFindHandle, FindInfo)
      bNextLoop = (lTemp <> ERROR_NO_MORE_FILES) And (lTemp <> 0)
      
    Loop While bNextLoop
    
    'Close down the file handle
    FindClose lFindHandle
  End If

  FolderSize = dSize

End Function
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top