delphi – 删除具有非空子目录和文件的目录
发布时间:2020-12-15 09:38:45 所属栏目:大数据 来源:网络整理
导读:如何删除一个包含某些文件和一些非空子目录的目录. 我试过 SHFileOperation Function .它在 Windows 7 有一些兼容性问题. 然后我尝试了 IFileOperation Interface .但它在Windows XP中不兼容. 然后我按照 David Heffernan 的建议尝试了以下代码: procedure
如何删除一个包含某些文件和一些非空子目录的目录.
我试过 SHFileOperation Function.它在 Windows 7有一些兼容性问题. 然后我尝试了 IFileOperation Interface.但它在Windows XP中不兼容. 然后我按照 David Heffernan的建议尝试了以下代码: procedure TMainForm.BitBtn01Click(Sender: TObject); var FileAndDirectoryExist: TSearchRec; ResourceSavingPath : string; begin ResourceSavingPath := (GetWinDir) + 'WebWallpaper'; 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; 但它没有在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 + '*',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; 这将删除目录及其内容.您需要遍历顶级目录,然后为找到的每个子目录调用此函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |