如何删除一个包含某些文件和一些非空子目录的目录.
我试过SHFileOperation函数.它在Windows 7中存在一些兼容性问题.
然后我尝试了IFileOperation接口.但它在Windows XP中不兼容.然后我按照David Heffernan的建议尝试了以下代码:
procedure TMainForm.BitBtn01Click(Sender: TObject);
var
FileAndDirectoryExist: TSearchRec;
ResourceSavingPath : string;
begin
ResourceSavingPath := (GetWinDir) + 'Web\Wallpaper\';
if FindFirst(ResourceSavingPath + '\*', faAnyFile, FileAndDirectoryExist) = 0 then
try
repeat
if (FileAndDirectoryExist.Name <> '.') and (FileAndDirectoryExist.Name <> '..') then
if (FileAndDirectoryExist.Attr and faDirectory) <> 0 then
//it's a directory, empty it
ClearFolder(ResourceSavingPath +'\' + FileAndDirectoryExist.Name, mask, recursive)
else
//it's a file, delete it
DeleteFile(ResourceSavingPath + '\' + FileAndDirectoryExist.Name);
until FindNext(FileAndDirectoryExist) <> 0;
//now that this directory is empty, we can delete it
RemoveDir(ResourceSavingPath);
finally
FindClose(FileAndDirectoryExist);
end;
end;
Run Code Online (Sandbox Code Playgroud)
但它没有在ClearFolder,掩码和递归中编译提到错误为Undeclared Identifier .我的要求是"如果WALLPAPER文件夹下存在任何子文件夹,它将被删除".相同的子文件夹可以包含任意数量的非空子文件夹或文件.
好吧,对于初学者来说,SHFileOperation
在Windows 7或Windows 8上没有兼容性问题.是的,现在建议您使用IFileOperation
.但是如果你想支持像XP这样的旧操作系统,那么你可以而且应该只是打电话SHFileOperation
.它工作并将继续工作.在Windows 7和Windows 8上使用它是完全正常的,如果它从Windows中删除,我会吃掉我的帽子.微软竭尽全力保持向后兼容性.所以,SHFileOperation
在我看来,这是你最好的选择.
您的FindFirst
基础方法失败,因为您需要将其放在单独的函数中以允许递归.我在其他答案中发布的代码不完整.这是一个完整的版本:
procedure DeleteDirectory(const Name: string);
var
F: TSearchRec;
begin
if FindFirst(Name + '\*', faAnyFile, F) = 0 then begin
try
repeat
if (F.Attr and faDirectory <> 0) then begin
if (F.Name <> '.') and (F.Name <> '..') then begin
DeleteDirectory(Name + '\' + F.Name);
end;
end else begin
DeleteFile(Name + '\' + F.Name);
end;
until FindNext(F) <> 0;
finally
FindClose(F);
end;
RemoveDir(Name);
end;
end;
Run Code Online (Sandbox Code Playgroud)
这将删除目录及其内容.您需要遍历顶级目录,然后为找到的每个子目录调用此函数.