Search code examples
c++cwindowswinapiwin32-process

Why is RemoveDirectory function not deleting the top most folder?


refer: codeguru.com/forum/showthread.php?t=239271

When using the function below to delete folders, all folders, subfolders and files are getting deleted except for the top most folder. Say for the path c:\folder1\folder2 every thing under folder2 is deleted except for 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
}  

Any help in finding the issue is appreciated. During debugging I noticed that the FindClose function was successfully closing the file handle but GetLastError was returning 32 ("The process cannot access the file because it is being used by another process") However I have no clue after trying with process explorer.


Solution

  • Whilst you can delete a directory this way, it's simpler to let the system do it for you by calling SHFileOperation passing FO_DELETE. Remember that you must double null-terminate the string you pass to this API.