Mega Code Archive

 
Categories / Delphi / Files
 

FilesDirectories

Title: Files/Directories Question: How can delete a directory with its files and subdirectories? Answer: In Delphi there is a function called RemoveDir that delete empty directories. But what about directories that has files and sub-sub... directories? For this reason I implemented my own function to act like the normal RemoveDir function but with extra functionality to delete any files or subdirectories in side that directory. Function MyRemoveDir(sDir : String) : Boolean; var iIndex : Integer; SearchRec : TSearchRec; sFileName : String; begin Result := False; sDir := sDir + '\*.*'; iIndex := FindFirst(sDir, faAnyFile, SearchRec); while iIndex = 0 do begin sFileName := ExtractFileDir(sDir)+'\'+SearchRec.Name; if SearchRec.Attr = faDirectory then begin if (SearchRec.Name '' ) and (SearchRec.Name '.') and (SearchRec.Name '..') then MyRemoveDir(sFileName); end else begin if SearchRec.Attr faArchive then FileSetAttr(sFileName, faArchive); if NOT DeleteFile(sFileName) then ShowMessage('Could NOT delete ' + sFileName); end; iIndex := FindNext(SearchRec); end; FindClose(SearchRec); RemoveDir(ExtractFileDir(sDir)); Result := True; end; Example: if NOT MyRemoveDir('D:\myDir') then ShowMessage('Can NOT delete dir'); Note: (1) Any system/hidden/read-only files will be deleted.