Recent

Author Topic: [CLOSED] Recursively delete empty folders  (Read 1343 times)

pcurtis

  • Hero Member
  • *****
  • Posts: 935
[CLOSED] Recursively delete empty folders
« on: January 26, 2022, 12:35:36 pm »
How do I recursively delete empty folders?
« Last Edit: January 26, 2022, 03:36:41 pm by pcurtis »
Windows 10 20H2
Laz 2.2.0
FPC 3.2.2

Zvoni

  • Hero Member
  • *****
  • Posts: 1173
Re: Recursively delete empty folders
« Reply #1 on: January 26, 2022, 12:54:59 pm »
Hmm..... Use FindAllFiles (or something similar) to list all directories beneath your starting point, count files in each "end leaf" of that tree, if count=0 then NukeFolder

btw: When checking those "end leaves" of the tree, you have to start from the deepest level

example (result of FindAllFiles):
/home/zvoni/documents/folder1/folder2/folder3/folder4
/home/zvoni/documents/folder1/folder2/folder3
/home/zvoni/documents/folder1/folder2
etc.
Folder4 is empty --> delete it
Folder3 is NOW empty --> delete it
Folder2 NOW contains only a single txt-file --> Leave that whole Branch, since Folder1, documents, Zvoni, home won't be empty
etc.

EDIT: btw: https://forum.lazarus.freepascal.org/index.php?topic=38849.0
https://stackoverflow.com/questions/63592784/how-to-remove-empty-directory-recursively-in-delphi
« Last Edit: January 26, 2022, 01:04:38 pm by Zvoni »
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

pcurtis

  • Hero Member
  • *****
  • Posts: 935
Re: Recursively delete empty folders
« Reply #2 on: January 26, 2022, 03:35:39 pm »
Thanks.

I used this

Code: Pascal  [Select][+][-]
  1. function DirectoryIsEmpty(Directory: string): Boolean;
  2. var
  3.   SR: TSearchRec;
  4.   i: Integer;
  5. begin
  6.   Result := False;
  7.   FindFirst(IncludeTrailingPathDelimiter(Directory) + '*', faAnyFile, SR);
  8.   for i := 1 to 2 do
  9.     if (SR.Name = '.') or (SR.Name = '..') then
  10.       Result := FindNext(SR) <> 0;
  11.   FindClose(SR);
  12. end;
  13.  
  14. procedure TForm1.FormCreate(Sender: TObject);
  15. var
  16.   DirList: TStringList;
  17.   iTemp: Integer;
  18. begin
  19.   DirList:= TStringList.Create;
  20.   FindAllDirectories(DirList, 'd:\test\', True);
  21.   for iTemp:= DirList.Count - 1 downto 0 do
  22.     begin
  23.       if DirectoryIsEmpty(DirList[iTemp]) then
  24.         DeleteDirectory(DirList[iTemp], False);
  25.     end;
  26.   DirList.Free;
  27. end;  
  28.  
Windows 10 20H2
Laz 2.2.0
FPC 3.2.2

 

TinyPortal © 2005-2018