Getting the total directory size in bytes
   


To get the total size in bytes of a directory, call DirSize() below. This will return the number of bytes found for all files and subdirectories of a directory. Read the comment for the usage. To get the total size of a disk, see GetDiskSize().

{$DEFINE Delphi3Below} 
{$IFDEF VER130} //Delphi 5
  {$UNDEF Delphi3Below}
{$ELSE}
  {$IFDEF VER120} //Delphi 4
    {$UNDEF Delphi3Below}
  {$ENDIF}
{$ENDIF}

uses StdCtrls, FileCtrl;

var
  
{$IFDEF Delphi3Below}
  TotalSize: comp;
  
{$ELSE}
  TotalSize: Int64;
  
{$ENDIF}

{$IFDEF Delphi3Below}
function DirSize(Path: string; ScanLabel, SizeLabel: TLabel): comp;
{$ELSE}

function DirSize(Path: string; ScanLabel, SizeLabel: TLabel): Int64;
{$ENDIF}

{ func to return the total number of bytes found in a directory. }
{ You can pass 2 TLabels for a progress while scanning:
  ScanLabel: will display the current path being scanned
  SizeLabel: will display the total size so far counted.
  If you don't want to use either Labels, pass nil to both. You
  can still use returned value to read the total size. Example:
  (For Delphi 4/5)
    TotalSize := 0;
    Label1.Caption := IntToStr(DirSize('C:\Windows', nil, nil)) + ' bytes'; 
  (For Delphi 3)
    TotalSize := 0;
    Label1.Caption := FloatToStr(DirSize('C:\Windows', nil, nil)) + ' bytes'; 
  (It is a little faster this way.)
  Note: you MUST initialize the global TotalSize variable to 0 before 
  using this function. }

var
  Res: Integer;
  SR: TSearchRec;
begin
  Result := TotalSize;
  if Copy(Path, Length(Path), 1) <> '\' then
    Path := Path + '\';
  if not DirectoryExists(Path) then
    begin
      MessageDlg('Directory does not exist: ' + Path, mtError, [mbOK], 0);
      Exit;
    end;
  if ScanLabel <> nil then
    begin
      ScanLabel.Caption := 'Scanning ' + Path; 
      ScanLabel.Update;
    end;
  Res := FindFirst(Path + '*.*', faAnyFile, SR);
  try
    while Res = 0 do
      begin
        if (SR.Name [1] <> '.') and (SR.Name [1] <> '..') then
          begin 
            if ((SR.Attr and faDirectory) <> 0) then 
              DirSize(Path + SR.Name + '\', ScanLabel, SizeLabel)
            else 
              TotalSize := TotalSize + SR.Size;
          end
        Res := FindNext(SR);
        if SizeLabel <> nil then
          begin 
            
{$IFDEF Delphi3Below}
            SizeLabel.Caption := 'Total size: ' + FloatToStr(TotalSize) + ' bytes';
            
{$ELSE}
            SizeLabel.Caption := 'Total size: ' + IntToStr(TotalSize) + ' bytes';
            
{$ENDIF}
            SizeLabel.Update; 
          end
      end;
  finally
    FindClose(SR);
  end;
  Result := TotalSize;
end;



Blue Orb Software
[email protected]