If you ended up looking for this, then you probably came to the conclusion that Windows.RemoveDirectory() can not remove a directory that has files/directories in it.
About.com proposes the following solution: http://delphi.about.com/cs/adptips1999/a/bltip1199_2.htm
I can assure you that this solution is valid and works. However, the code as it is proposed there will move the deleted folder into the recycle bin which is something you will want to avoid more often than not. The following code I modified to remove that effect:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function RemoveDirectory(const Path: string): Boolean; var SHFileOpStruct: TSHFileOpStruct; DirBuf: array[0..255] of Char; begin if DirectoryExists(Path) then try FillChar(SHFileOpStruct, Sizeof(SHFileOpStruct), 0); FillChar(DirBuf, Sizeof(DirBuf), 0); StrPCopy(DirBuf, Path); with SHFileOpStruct do begin Wnd := 0; pFrom := @DirBuf; wFunc := FO_DELETE; fFlags := FOF_NOCONFIRMATION or FOF_SILENT; end; Result := SHFileOperation(SHFileOpStruct) = 0; except Result := False; end; end; |
Another way of doing this is recursing through all directories and removing all files before you remove the directories as seen here, but I imagine that might be slower as in the method above, the OS takes care of that internally:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function RemoveDirectory(const Path: string): Boolean; var sRec: TSearchRec; t: string; begin if DirectoryExists(Path) then try t := IncludeTrailingPathDelimiter(Path); if FindFirst(t + '*.*', faNormal or faDirectory, sRec) = 0 then begin repeat if ((sRec.Attr and faDirectory) <> 0) and (sRec.Name <> '.') and (sRec.Name <> '..') then RemoveDirectory(t + sRec.Name) else DeleteFile(t + sRec.Name); until FindNext(sRec) <> 0; FindClose(sRec); end; Result := Windows.RemoveDirectory(PChar(t)); except Result := False; end; end; |