The simplest thing to do is to call TDirectory.Delete(Dir, True)
.
TDirectory
is found in IOUtils
which is quite a recent RTL addition.
The True
flag is passed to the Recursive
parameter which means that the contents of the directories are empied before the directory is removed, an essential part of deleting directories.
In a comment you tell us that you use Delphi 7 and so this cannot be used.
Your code looks mostly fine. However, you don't mean:
(Result.Attr and faAnyFile <> faDirectory)
I think you mean:
(Result.Attr and faDirectory <> faDirectory)
I would probably write it as follows:
procedure TMyForm.Remove(const Dir: string);
var
Result: TSearchRec;
begin
if FindFirst(Dir + '*', faAnyFile, Result) = 0 then
begin
Try
repeat
if (Result.Attr and faDirectory) = faDirectory then
begin
if (Result.Name <> '.') and (Result.Name <> '..') then
Remove(Dir + '' + Result.Name)
end
else if not DeleteFile(Dir + '' + Result.Name) then
RaiseLastOSError;
until FindNext(Result) <> 0;
Finally
FindClose(Result);
End;
end;
if not RemoveDir(Dir) then
RaiseLastOSError;
end;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…