Forum > General

[CLOSED] Recursively delete empty folders

(1/1)

pcurtis:
How do I recursively delete empty folders?

Zvoni:
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

pcurtis:
Thanks.

I used this


--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---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; procedure TForm1.FormCreate(Sender: TObject);var  DirList: TStringList;  iTemp: Integer;begin  DirList:= TStringList.Create;  FindAllDirectories(DirList, 'd:\test\', True);  for iTemp:= DirList.Count - 1 downto 0 do    begin      if DirectoryIsEmpty(DirList[iTemp]) then        DeleteDirectory(DirList[iTemp], False);    end;  DirList.Free;end;   

Navigation

[0] Message Index

Go to full version