Mega Code Archive

 
Categories / Delphi / Files
 

How to check if a given folder is empty

Title: How to check if a given folder is empty Question: Ever needed to check if a folder is empty or not? That's my way of doing. I think it's really fast, but not benchmarked yet. Answer: You'll need to add the "FileCtrl" and "SysUtils" units in your uses clausole. uses FileCtrl, SysUtils; and then declaring this, the function you need. function IsEmptyFolder(fld:string):boolean; var sr:tsearchrec; r:integer; begin fld:=IncludeTrailingBackSlash(fld); result:=false; if(DirectoryExists(fld))then begin result:=true; r:=findfirst((fld+'*.*'),faAnyFile,sr); while((r=0)and(result))do begin // Revision 2: // checks for system folders "." and ".." that always exists // inside an empty folder. if((SR.Attr and faDirectory)0)then begin if((sr.name'.')and(sr.name'..'))then begin result:=false; end; end else begin result:=false; end; r:=findnext(sr); end; // Revision 1: // this prevents compiler by using the API defined in windows unit, // that will raise a compiler error like this: // [Error]:Incompatible types: 'Cardinal' and 'TSearchRec' sysutils.findclose(sr); end; end; The function only requires one parameter: the folder you want to check. It returns "True" if the folder is empty or "False" if the folder contains something.