DelphiFAQ Home Search:

Recursively delete a group of files and subdirectories

 

comments3 comments. Current rating: 5 stars (2 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!

 

 

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:
photo Add a picture:

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.