Find Empty Folders

Posted:
May 30th, 2009, 2:07 pm
by w2m
How can you find folders without any files (empty folders) with TFindFile?
- Code: Select all
function IsFolderEmpty( const AFolder: string ): boolean;
// returns true if a given folder is empty, false otherwise
var
SearchRec: TSearchRec;
begin
try
result := ( FindFirst( AFolder + '\*.*', faAnyFile, searchRec ) = 0 ) and
( FindNext( SearchRec ) = 0 ) and
( FindNext( SearchRec ) <> 0 );
finally
FindClose( SearchRec );
end;
end;
Re: Find Empty Folders

Posted:
May 30th, 2009, 5:43 pm
by Kambiz
Here is a sample.
- Code: Select all
function IsFolderEmpty(const Path: String): Boolean;
var
SearchRec: TSearchRec;
begin
Result := True;
if FindFirst(Path + '\*.*', faAnyFile, SearchRec) = 0 then
try
repeat
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
begin
Result := False;
Exit;
end;
until FindNext(SearchRec) <> 0;
finally
FindClose(SearchRec);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Clear;
FindFile1.Criteria.Clear;
FindFile1.Criteria.Attributes.Directory := fsSet;
FindFile1.Criteria.Files.Location := 'C:\';
FindFile1.Criteria.Files.Subfolders := True;
FindFile1.Execute;
end;
procedure TForm1.FindFile1FileMatch(Sender: TObject;
const FileInfo: TFileDetails);
var
FullPath: String;
begin
FullPath := FileInfo.Location + FileInfo.Name;
if IsFolderEmpty(FullPath) then
Memo1.Lines.Add(FullPath);
end;
I didn't expect so many empty folders are on my computers.

Re: Find Empty Folders

Posted:
May 30th, 2009, 9:48 pm
by w2m
Thanks.
Yes me too.. lots of empty folders.
I wonder if FileFind can find duplicate files? Have you tried that?
Bill
Re: Find Empty Folders

Posted:
May 30th, 2009, 10:34 pm
by Kambiz
No it can't. You have to do it by yourself because FindFile doesn't store FileInfo record of found files.