DelphiFAQ Home Search:

Recursively delete a group of files and subdirectories

 

comments6 comments. Current rating: 5 stars (3 votes). Leave comments and/ or rate it.

Use the following routine do delete all files matching a certain mask within a given directory.
If you set the third parameter to TRUE, subdirectires are scanned/ deleted also.

{**Summary ======================================================
    NAME    :   DeleteFiles
    PARAMS  :   const Path, Mask : string; recursive : boolean

    RETURNS :   -
    PURPOSE :   delete several files with joker.
                Optional recursive = search in subdirectories.                

    EXAMPLE :   DeleteFiles ('c:\temp\', '*.txt', True);
    UPDATES :

    NOTES   :
    CODED   :   PT  15.10.96
  ===============================================================*}
procedure DeleteFiles (const Path, Mask : string; recursive : boolean);
var
  Result    : integer;
  SearchRec : TSearchRec;
begin
  Result := FindFirst(Path + Mask, faAnyFile - faDirectory, SearchRec);
  while Result = 0 do
  begin
    if not DeleteFile (Path + SearchRec.name) then
    begin
      FileSetAttr (Path + SearchRec.name, 0); { reset all flags }
      DeleteFile (Path + SearchRec.name);
    end;
    Result := FindNext(SearchRec);
  end;
  FindClose(SearchRec);

  if not recursive then
    exit;

  Result := FindFirst(Path + '*.*', faDirectory, SearchRec);
  while Result = 0 do
  begin
    if (SearchRec.name <> '.') and (SearchRec.name <> '..') then
    begin
      FileSetAttr (Path + SearchRec.name, faDirectory);
      DeleteFiles (Path + SearchRec.name + '\', Mask, TRUE);
      RmDir (Path + SearchRec.name);
    end;
    Result := FindNext(SearchRec);
  end;
  FindClose(SearchRec);
end;

Comments:

2006-10-05, 20:32:05
randomyzer@gmail.com from Cuba  
rating
add {$I-} directive before rmdir to ignore errors:

{$I-}
RmDir (Path + SearchRec.Name);
2007-01-27, 01:42:15
[hidden] from Turkey  
rating
It was a great help. Thanks
2007-09-26, 15:22:49
anonymous  
thanks bro, this is brilliant code saved me a ton of time, THANK YOU SO MUCH!
2011-10-12, 20:38:18
anonymous from Croatia/Hrvatska  
Remove const from Path and add:
Path := IncludeTrailingPathDelimiter(Path);

It is worse to delete wrong directory than to add accidentally forgotten trailing backslash when calling the function where Path for example is 'C:\temp'. Also adds the code flexibility to call with path without trailing slash.

Here is also C++ translation for future googlers (like myself).

void DeleteFiles(const UnicodeString &Path, const UnicodeString &Mask, bool Recursive)
{
int Result;
TSearchRec SearchRec;

Result = FindFirst(Path + Mask, faAnyFile - faDirectory, SearchRec);
while (Result == 0)
    {
    if (!DeleteFile(Path + SearchRec.Name))
        {
        FileSetAttr(Path + SearchRec.Name, 0); // reset all flags
        DeleteFile (Path + SearchRec.Name);
        }
    Result = FindNext(SearchRec);
    }

FindClose(SearchRec);

if (!Recursive) return;

Result = FindFirst(Path + '*.*', faDirectory, SearchRec);
while (Result == 0)
    {
    if (SearchRec.Name != '.' && SearchRec.Name != '..')
        {
        FileSetAttr(Path + SearchRec.Name, faDirectory);
        DeleteFiles(Path + SearchRec.Name + '\\', Mask, true);
        RmDir     (Path + SearchRec.Name);
        }
    Result = FindNext(SearchRec);
    }

FindClose(SearchRec);
}
2011-10-21, 12:57:02
anonymous  
You should replace RmDir with SysUtils.RemoveDir which is new VCL style unlike older RmDir. Also if you use {$I-} and read IOResult this function is NOT thread safe. So RemoveDir is probably a better choice.
2016-07-25, 10:19:50
anonymous from Spain  
rating

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: