Delete all files and folders recursively using Delphi

Viewed 28495

I am trying to delete a folder and all of its sub-folders recursively but it is not working at all, so can someone please check the code and tell me what I am doing wrong here?

I am running this code through D7 under Windows XP

if FindFirst (FolderPath + '\*', faAnyFile, f) = 0 then
      try             
         repeat

            if (f.Attr and faDirectory) <> 0 then
              begin
                    if (f.Name <> '.') and (f.Name <> '..') then
                      begin                            
                        RemoveDir(FolderPath +'\'+ f.Name);
                      end
                    else
                      begin
                        //Call function recursively...
                        ClearFolder(FolderPath +'\'+ f.Name, mask, recursive);
                      end;
              end;

         until (FindNext (f) <> 0);
      finally
        SysUtils.FindClose (f)
      end;
end;
3 Answers

Starting with Delphi 2010 there is a TDirectory record in System.IOUtils unit with some methods, including

TDirectory.Delete('path_to_dir', True);
Related