Title: Calculate Size of a Directoy and Sub-Directories
Question: This function returns the size in bytes of the total files in a given directory path. The function parameters are ...
ADirName : string
This is the name path to the desired directory. It can include or exclude the trailing backslash as it is resolved internally.
ARecurseDirs : boolean = true
This denotes whether to recurse Sub-Directories or not. By default Sub-Directories will recursively be processed.
Examples
iSize := DirSize('c:\temp'); // Will recurse sub-dirs
iSize := DirSize('c:\temp\',true) // Same as above
iSize := DirSize('\program files\',false); // No sub-dir recurse
Answer:
// ===========================================
// Return Total size of files in directory
// in bytes
// ===========================================
function DirSize(const ADirName : string;
ARecurseDirs : boolean = true) : integer;
const FIND_OK = 0;
var iResult : integer;
// ====================
// Recursive Routine
// ====================
procedure _RecurseDir(const ADirName : string);
var sDirName : string;
rDirInfo : TSearchRec;
iFindResult : integer;
begin
sDirName := IncludeTrailingPathDelimiter(ADirName);
iFindResult := FindFirst(sDirName + '*.*',faAnyFile,rDirInfo);
while iFindResult = FIND_OK do begin
// Ignore . and .. directories
if (rDirInfo.Name[1] '.') then begin
if (rDirInfo.Attr and faDirectory = faDirectory) and
ARecurseDirs then
_RecurseDir(sDirName + rDirInfo.Name) // Keep Recursing
else
inc(iResult,rDirInfo.Size); // Accumulate Sizes
end;
iFindResult := FindNext(rDirInfo);
if iFindResult FIND_OK then FindClose(rDirInfo);
end;
end;
// DirSize Main
begin
Screen.Cursor := crHourGlass;
Application.ProcessMessages;
iResult := 0;
_RecurseDir(ADirName);
Screen.Cursor := crDefault;
Result := iResult;
end;