README.md

December 4, 2022 ยท View on GitHub

GetPathSize

Description

Very fast recursive function to calculate the size of a directory (folder). This code is simple and built for speed. This code does NOT use the FileSystemObject because it is NOT installed on all PCs, therefore you cannot write code using it (unless you include the scrrun.dll - Microsoft Scripting Runtime with your application). **Update - I added the search options for System, Hidden, and Read-Only files so the result will truely match the same number of bytes that is displayed in Windows Explorer properties.

More Info

sPathName - The path to the directory

The size (number of bytes) as a Double

Submitted On
ByRobert E. Phelps
LevelIntermediate
User Rating4.9 (44 globes from 9 users)
CompatibilityVB 3.0, VB 4.0 (16-bit), VB 4.0 (32-bit), VB 5.0, VB 6.0
CategoryFiles/ File Controls/ Input/ Output
WorldVisual Basic
Archive File

Source Code

Public Function GetPathSize(ByRef sPathName As String) As Double
 Dim sFileName As String
 Dim dSize As Double
 Dim asFileName() As String
 Dim i As Long
 ' Enumerate DirNames and FileNames
 If StrComp(Right$(sPathName, 1), "\", vbBinaryCompare) <> 0 Then sPathName = sPathName & "\"
 sFileName = Dir$(sPathName, vbDirectory + vbHidden + vbSystem + vbReadOnly)
 Do While Len(sFileName) > 0
  If StrComp(sFileName, ".", vbBinaryCompare) <> 0 And StrComp(sFileName, "..", vbBinaryCompare) <> 0 Then
   ReDim Preserve asFileName(i)
   asFileName(i) = sPathName & sFileName
   i = i + 1
  End If
  sFileName = Dir
 Loop
 If i > 0 Then
  For i = 0 To UBound(asFileName)
   If (GetAttr(asFileName(i)) And vbDirectory) = vbDirectory Then
    ' Add dir size
    dSize = dSize + GetPathSize(asFileName(i))
   Else
    ' Add file size
    dSize = dSize + FileLen(asFileName(i))
   End If
  Next
 End If
 GetPathSize = dSize
End Function