Posted by John, DelphiLand Team on August 06, 2007
In Reply to Clearing A Folder posted by Peter Howes on
August 06, 2007
: Is there a simple Delphi4.0 equivalent to the following DOS command:
: delete c:\f\p\*.*
: In other words, is there a command, or procedure, to delete all files from a sub-directory?
Delphi itself doesn't have a routine for deleting multiple files at once, but you can use the Windows function (a so-called API function) SHFileOperation.
The Delphi "interface" for SHFileOperation is defined in Delphi's unit SHELLAPI, so firstly add SHELLAPI to the uses-clause on top of your unit:
interface uses Windows, Messages, ..., SHELLAPI;
Let's wrap this function in a procedure that is suitable for re-use. Add the following function to the implementation section of the unit:
procedure DelFilesFromDir(Directory, FileMask: string; DelSubDirs: Boolean); var SourceLst: string; FOS: TSHFileOpStruct; begin FillChar(FOS, SizeOf(FOS), 0); FOS.Wnd := Application.MainForm.Handle; FOS.wFunc := FO_DELETE; SourceLst := Directory + '\' + FileMask + #0; FOS.pFrom := PChar(SourceLst); if not DelSubDirs then FOS.fFlags := FOS.fFlags OR FOF_FILESONLY; // Remove the next line if you want a confirmation dialog box FOS.fFlags := FOS.fFlags OR FOF_NOCONFIRMATION; // Add the next line for a "silent operation" (no progress box) // FOS.fFlags := FOS.fFlags OR FOF_SILENT; SHFileOperation(FOS); end;
Below is a source code example that deletes all the files from directory (folder) C:\TEST, without deleting the subdirectories that might be present in C:\TEST (if you also want to delete all of the subdirectories and their contents, specify TRUE for the last parameter of DelFilesFromDir) :
procedure TForm1.Button1Click(Sender: TObject); begin DelFilesFromDir('C:\TEST', '*.*', FALSE); end;
If you also want to delete all of the subdirectories of C:\TEST and their contents, specify: DelFilesFromDir('C:\TEST', '*.*', TRUE);
John, DelphiLand Team