参考:codeguru.com/forum/showthread.php?t=239271为什么RemoveDirectory函数不会删除最顶层的文件夹?
当使用下面的功能删除文件夹时,除最上面的文件夹外,所有文件夹,子文件夹和文件都将被删除。对于路径c:\folder1\folder2
说,除folder2
之外,folder2
之下的所有东西都被删除。
BOOL DeleteDirectory(const TCHAR* sPath)
{
HANDLE hFind; // file handle
WIN32_FIND_DATA FindFileData;
TCHAR DirPath[MAX_PATH];
TCHAR FileName[MAX_PATH];
_tcscpy(DirPath,sPath);
_tcscat(DirPath,_T("\\"));
_tcscpy(FileName,sPath);
_tcscat(FileName,_T("\\*")); // searching all files
int nRet = 0;
hFind = FindFirstFile(FileName, &FindFileData); // find the first file
if(hFind != INVALID_HANDLE_VALUE)
{
do
{
if(IsDots(FindFileData.cFileName))
continue; //if not directory continue
_tcscpy(FileName + _tcslen(DirPath), FindFileData.cFileName);
if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
// we have found a directory, recurse
if(!DeleteDirectory(FileName))
break; // directory couldn't be deleted
}
else
{
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
_wchmod(FileName, _S_IWRITE); // change read-only file mode
if(!DeleteFile(FileName))
break; // file couldn't be deleted
}
}while(FindNextFile(hFind, &FindFileData));
nRet = FindClose(hFind); // closing file handle
}
return RemoveDirectory(sPath); // remove the empty (maybe not) directory and returns zero when RemoveDirectory function fails
}
任何帮助找到问题的赞赏。 在调试过程中,我注意到,FindClose
功能被成功关闭文件句柄,但GetLastError
返航32(“因为它正由另一个进程的进程无法访问文件”),但我有一个过程的探索者试图后没有任何线索。
在DeleteFile失败后立即调用GetLastError并找出它给出的错误。这应该可以帮助你解决这个问题。 – Jay 2012-03-13 12:15:36