Monday, June 25, 2007

Calculate Size of Folders, Sub folders and files


function DirSize(const ADirName : string; ARecurseDirs : boolean = true): integer;
const
FIND_OK = 0;
var
nResult : integer;

procedure _RecursiveDir(const ADirName : string);
var
sDirName : String;
rDirInfo : TSearchRec;
nFindResult : Integer;
begin
sDirName := IncludeTrailingPathDelimiter(ADirName);
nFindResult := FindFirst(sDirName + '*.*',faAnyFile,rDirInfo);

while nFindResult = FIND_OK do
begin
// Ignore . and .. directories
if (rDirInfo.Name[1] <> '.') then
begin
if (rDirInfo.Attr and faDirectory = faDirectory) and ARecurseDirs then
RecursiveDir(sDirName + rDirInfo.Name) // Keep Recursing
else
inc(nResult, rDirInfo.Size); // Accumulate Sizes
end;

nFindResult := FindNext(rDirInfo);
if nFindResult <> FIND_OK then
FindClose(rDirInfo);
end;
end;

// DirSize Main
begin
Screen.Cursor := crHourGlass;
Application.ProcessMessages;
nResult := 0;
RecursiveDir(ADirName);
Screen.Cursor := crDefault;

Result := nResult;
end;

No comments: