Find Empty Folders

Please post bug reports, feature requests, or any question regarding the DELPHI AREA projects here.

Find Empty Folders

Postby w2m » May 30th, 2009, 2:07 pm

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;
w2m
w2m
Senior Member
Senior Member
 
Posts: 76
Joined: March 8th, 2003, 7:11 pm
Location: New York, USA

Re: Find Empty Folders

Postby Kambiz » May 30th, 2009, 5:43 pm

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. :)
Kambiz
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2429
Joined: March 7th, 2003, 7:10 pm

Re: Find Empty Folders

Postby w2m » May 30th, 2009, 9:48 pm

Thanks.

Yes me too.. lots of empty folders.

I wonder if FileFind can find duplicate files? Have you tried that?

Bill
w2m
w2m
Senior Member
Senior Member
 
Posts: 76
Joined: March 8th, 2003, 7:11 pm
Location: New York, USA

Re: Find Empty Folders

Postby Kambiz » May 30th, 2009, 10:34 pm

No it can't. You have to do it by yourself because FindFile doesn't store FileInfo record of found files.
Kambiz
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2429
Joined: March 7th, 2003, 7:10 pm


Return to DELPHI AREA Projects

Who is online

Users browsing this forum: No registered users and 6 guests

cron