Search code examples
delphidirectory

How to remove empty directory recursively in Delphi


A parent directory D:\AAA has 2 child empty Directory D:\AAA\BB1 and D:\AAA\BB2 my requirement is how to remove empty Directory recursively. Here are two function found on internet as below : //remove empty Directory recursively

function RemoveEmptyDirectory(path: string) : Boolean;
var
  MySearch: TSearchRec;
  Ended: Boolean;
begin
  if FindFirst(path + '\*.*', faDirectory, MySearch) = 0 then
  begin
    repeat
      if ((MySearch.Attr and faDirectory) = faDirectory) and
        (MySearch.Name[1] <> '.') then
      begin
        if DirectoryIsEmpty(path + '\' + MySearch.Name) then
          TDirectory.Delete(path + '\' + MySearch.Name)
        else
        begin
          RemoveEmptyDirectory(path + '\' + MySearch.Name);
          if DirectoryIsEmpty(path + '\' + MySearch.Name) then
            RemoveEmptyDirectory(path + '\' + MySearch.Name);
        end;
      end;
    until FindNext(MySearch) <> 0;
    FindClose(MySearch);
  end;
end;

// check directory is empty or not

function DirectoryIsEmpty(Directory: string): Boolean;
var
  SR: TSearchRec;
  i: Integer;
begin
  Result := False;
  FindFirst(IncludeTrailingPathDelimiter(Directory) + '*', faAnyFile, SR);
  for i := 1 to 2 do
    if (SR.Name = '.') or (SR.Name = '..') then
      Result := FindNext(SR) <> 0;
  FindClose(SR);
end;

My problem is here : at first run function RemoveEmptyDirectory will found D:\AAA is not empty, then will run send round (recursively way), After remove 2 child directory D:\AAA\BB1 and D:\AAA\BB2, the parent will become an empty Directory, Back to first round place the function DirectoryIsEmpty report the parent is not an empty directory!!!! Why !!!! Is windows system still not change the directory state ???

So, is there any good suggestion that could meet my requirement.


Solution

  • You never check D:\AAA itself.

    Just make checking and deletion in the end:

    function RemoveEmptyDirectory(path: string) : Boolean;
    var
      MySearch: TSearchRec;
      Ended: Boolean;
    begin
      if FindFirst(path + '\*.*', faDirectory, MySearch) = 0 then
      begin
        repeat
          if ((MySearch.Attr and faDirectory) = faDirectory) and
            (MySearch.Name[1] <> '.') then
          begin
            if DirectoryIsEmpty(path + '\' + MySearch.Name) then
              TDirectory.Delete(path + '\' + MySearch.Name)
            else
            begin
              RemoveEmptyDirectory(path + '\' + MySearch.Name);
              if DirectoryIsEmpty(path + '\' + MySearch.Name) then
                RemoveEmptyDirectory(path + '\' + MySearch.Name);
            end;
          end;
        until FindNext(MySearch) <> 0;
        FindClose(MySearch);
      end;
    
      if DirectoryIsEmpty(path) then
        TDirectory.Delete(path);
    
    end;