That is, delete all files matching pattern within a given directory
Example, Delete all *.jpg files within DirectoryName
That is, delete all files matching pattern within a given directory
Example, Delete all *.jpg files within DirectoryName
procedure TForm1.Button1Click(Sender: TObject); begin Deletefiles(ExtractFilePath(ParamStr(0)),'*.jpg'); end;
procedure Deletefiles(APath, AFileSpec: string);
var
lSearchRec:TSearchRec;
lFind:integer;
lPath:string;
begin
lPath := IncludeTrailingPathDelimiter(APath);
lFind := FindFirst(lPath+AFileSpec,faAnyFile,lSearchRec);
while lFind = 0 do
begin
DeleteFile(lPath+lSearchRec.Name);
lFind := SysUtils.FindNext(lSearchRec);
end;
FindClose(lSearchRec);
end;
You can use the SHFileOperation function. The nice thing about using SHFileOperation is you have the option of deleting the files to the recycle bin and you get the normal API animations so the user will know what is going on. The downside is the delete will take a little longer than Jeff's code.
There are several wrappers out there. I use this free wrapper from BP Software. The entire wrapper file is only 220 lines and is easy to read and use. I don't install this as a component. I have found it easier to add this unit to my project and just Create and free the object as needed.
TSHFileOp (1.3.5.1) (3 KB)
May 31, 2006
TComponent that is a wrapper for the SHFileOperation API to copy, move, rename, or delete (with recycle-bin support) a file system object.
The file name parameter for SHFileOperation supports MS DOS style wildcards. So you can use the component like this:
FileOps := TSHFileOp.Create(self);
FileOps.FileList.Add(DirectoryName + '\*.jpg');
FileOps.HWNDHandle := self.Handle;
FileOps.Action := faDelete;
FileOps.SHOptions :=
[ofAllowUndo, ofNoConfirmation, ofFilesOnly, ofSimpleProgress];
FileOps.Execute;
I usually show the "Are you sure" message myself so I always pass the ofNoConfirmation flag so Windows does not ask again.
If you don't want to delete every jpg file or you need to delete from multiple directories you can add full file names or different paths with wild cards to the FileList string list before calling execute.
Here is the MSDN Page for SHFileOperation
Note that SHFileOperation has been replaced by IFileOperation starting with Windows Vista. I have continued to use SHFileOperation on Windows Vista without any problems.