删除目录,必须要保证该目录为空,即不能存在任何文件和子目录,才能删除该目录,否则删除不掉该目录。以下代码就是用来清空目录的,删除一个目录里的所有文件包括子目录。使用了递归调用。
procedure ClearDir(path: string);
var
FSearchRec: TSearchRec;
FindResult: shortint;
begin
FindResult := FindFirst(path + '*.*', faAnyFile, FSearchRec);
try
while FindResult = 0 do
begin
if ((FSearchRec.Attr and faDirectory) = faDirectory)
and (FSearchRec.Name <> '.') and (FSearchRec.Name <> '..') then
begin
ClearDir(path + FSearchRec.Name + '/');
RemoveDir(path + FSearchRec.Name);
end
else if (FSearchRec.Attr and faDirectory) <> faDirectory then
DeleteFile(path + FSearchRec.Name);
FindResult := FindNext(FSearchRec);
end;
finally
FindClose(FSearchRec);
end;
end;
FindFirst:命令对指定的文件名及属性搜索目录。
FindNext:命令返回与文件名及属性匹配的下一入口。
RemoveDir:删除目录,要保证该目录为空。
DeleteFile:删除文件。
关于这些函数详细解释请参考Delphi帮助。