Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming

How to find the size of a folder

By Zarko Gajic, About.com

Try the following function (it looks at hidden, system, archive, and normal files; it uses a recursive algorithm to look in all sub-directories also; just supply a starting directory as a parameter.

~~~~~~~~~~~~~~~~~~~~~~~~~
var
   DirBytes : integer;

function FolderSize(Dir:string):integer;
var
   SearchRec : TSearchRec;
   Separator : string;
begin
   Result:=0;
   if Copy(Dir,Length(Dir),1)='\' then
     Separator := ''
   else
     Separator := '\';

   if FindFirst(Dir+Separator+'*.*',faAnyFile,SearchRec) = 0 then begin
     if FileExists(Dir+Separator+SearchRec.Name) then begin
       DirBytes := DirBytes + SearchRec.Size;
     end else if DirectoryExists(Dir+Separator+SearchRec.Name) then begin
       if (SearchRec.Name<>'.') and (SearchRec.Name<>'..') then begin
         FolderSize(Dir+Separator+SearchRec.Name) ;
       end;
     end;
     while FindNext(SearchRec) = 0 do begin
       if FileExists(Dir+Separator+SearchRec.Name) then begin
         DirBytes := DirBytes + SearchRec.Size;
       end else if DirectoryExists(Dir+Separator+SearchRec.Name) then
       begin
         if (SearchRec.Name<>'.') and (SearchRec.Name<>'..') then begin
           FolderSize(Dir+Separator+SearchRec.Name) ;
         end;
       end;
     end;
   end;
   FindClose(SearchRec) ;
   Result:=DirBytes;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» How to convert BMP to WMF
« Is computer attached to a network?

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming

More from About.com

Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2002 Delphi Tips
  7. How to find the size of a folder

©2008 About.com, a part of The New York Times Company.

All rights reserved.