GetFolderSize()
Posted: Thu Feb 21, 2013 10:49 pm
This is a procedure to get the size of a folder and all sub-folders, it is non-recursive (in other words it does not need to call itself to handle sub folders).
While this example just gets the size of files / directory size or folder size and the size of sub-folders or sub-directories you can easily edit this to suit other needs.
EDIT: Added the delim suggestion by michel51 in http://www.purebasic.fr/english/viewtop ... 11#p405611 also added some extra checks on initial folder.
Code: Select all
;Public Domain
Procedure.q GetFolderSize(folder$)
Protected size.q,NewList folders.s(),directory.i,name$,delim$
If FileSize(folder$)=-2
CompilerIf #PB_Compiler_OS=#PB_OS_Windows
delim$="\"
CompilerElse ;MacOS or Linux
delim$="/"
CompilerEndIf
If Right(folder$,1)<>delim$
folder$=folder$+delim$ ;make sure the folder name ends with \ (WIndows) or / (Linux/Mac Os)
EndIf
AddElement(folders())
folders()=folder$ ;add the main folder to the list
While ListSize(folders())
folder$=folders()
DeleteElement(folders(),1) ;remove the folder from the list
directory=ExamineDirectory(#PB_Any,folder$,"")
If directory
While NextDirectoryEntry(directory)
If DirectoryEntryType(directory)=#PB_DirectoryEntry_File
size+DirectoryEntrySize(directory) ;add the entry size to total size so far
Else
name$=DirectoryEntryName(directory)
If (name$<>".") And (name$<>"..") ;. and .. are parent and current folder, we must ignore them to avoid a potential deadlock loop
AddElement(folders())
folders()=folder$+name$+delim$ ;add the folder to the list
EndIf
EndIf
Wend
FinishDirectory(directory)
EndIf
Wend
EndIf
ProcedureReturn size
EndProcedure
path.s = PathRequester("Choose a folder...", "") ;choose a folder ...
Debug GetFolderSize(path)
EDIT: Added the delim suggestion by michel51 in http://www.purebasic.fr/english/viewtop ... 11#p405611 also added some extra checks on initial folder.