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

IsDirectoryEmpty
Delphi function to Determine if a Directory is Empty (no files, no sub-folders)

By , About.com Guide

Delphi does not provide any "ready made" RTL function to test if a given directory (folder) is empty, i.e. contains no files or sub-folders.

Is Directory Empty

Here's a custom Delphi function which returns true if a given directory (folder) is empty.
//returns true if a given directory is empty, false otherwise
function IsDirectoryEmpty(const directory : string) : boolean;
var
  searchRec :TSearchRec;
begin
  try
   result := (FindFirst(directory+'\*.*', faAnyFile, searchRec) = 0) AND
             (FindNext(searchRec) = 0) AND
             (FindNext(searchRec) <> 0) ;
  finally
    FindClose(searchRec) ;
  end;
end;
Usage:
var
  directory : string;
  isEmpty : boolean;
begin
  //directory := 'c:\Program Files';
  directory := 'c:\New Folder';

  isEmpty := IsDirectoryEmpty(directory) ;

  ShowMessage(BoolToStr(isEmpty,true)) ;
end;
Note: the IsDirectoryEmpty does not check if a directory exists. Use the DirecotryExists to determine whether a given directory exists.

The IsDirectoryEmpty uses FindFirst, FindNext and FindClose to look "inside" the directory provided. Those three functions are explined in details in the "Searching For Files" article.

Delphi tips navigator:
» Convert RGB to TColor or How to Get More TColor values for Delphi
« How to Override Delphi Form's Restore Operation?

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2007 Tips
  7. IsDirectoryEmpty - Delphi function to Determine if a Directory is Empty (no files, no sub-folders)

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

All rights reserved.