Mega Code Archive

 
Categories / Delphi / Files
 

Deleting a directory and all the directories files and all the subfolders

Title: Deleting a directory and all the directories files and all the subfolders Question: How can I delete a directory and all the directories files? Answer: This function is based on the Peter Lieber article. But it is recursive and presented as a function. Return false if directory removing failed. The following function demonstrates deleting all the files in a directory and then the directory itself. Additional processing would be required to delete read only files and files that are in use. function DeleteDirectory(aDirectoryName : string; aContent : boolean = true) : boolean; var DirInfo: TSearchRec; r : Integer; begin result := true; if aContent then begin r := FindFirst(aDirectoryName + '\*.*', FaAnyfile, DirInfo); while (r = 0) and result do begin if (DirInfo.Attr and FaVolumeId FaVolumeID) then begin if (DirInfo.Attr and FaDirectory = FaDirectory) and (DirInfo.Name '.') and (DirInfo.Name '..') then result := DeleteDirectory(aDirectoryName + DirInfo.Name) else if (DirInfo.Attr and FaDirectory FaDirectory) then result := sysUtils.DeleteFile(aDirectoryName + '\' + DirInfo.Name); end; r := FindNext(DirInfo); end; SysUtils.FindClose(DirInfo); end; if Result then result := RemoveDir(aDirectoryName); end;