Search code examples
c++filevisual-c++mfcpermission-denied

Remove Directory function access denied


I am using the c++ code below to delete temporary files from a specific path.

C:\Users\falcon\AppData\Local\Temp\~GPG.TMP\

When inside the ~GPG.TMP folder exists some files, it deletes first and finally, it removes the folder itself. In this final step RemoveDirectory(sPathName) while I don't get any exceptions the folder is not actually deleted but when I am trying to access it (either externally or programmatically) I receive Error No 13 which is "Permission denied". Why does this happen?

void CFileOperation::DoDelete(CString sPathName)
{
    CFileFind ff;
    CString sPath = sPathName;

    if (CheckPath(sPath) == PATH_IS_FILE)
    {
        if (!CanDelete(sPath)) 
        {
            m_bAborted = true;
            return;
        }
        if (!DeleteFile(sPath)) throw new CFExeption(GetLastError());
        return;
    }

    PreparePath(sPath);
    sPath += "*.*";

    BOOL bRes = ff.FindFile(sPath);

    while(bRes)
    {
        bRes = ff.FindNextFile();
        if (ff.IsDots()) continue;
        if (ff.IsDirectory())
        {

            sPath = ff.GetFilePath();
            DoDelete(sPath);
        }
        else DoDelete(ff.GetFilePath());
    }
    ff.Close();

    if (!RemoveDirectory(sPathName) && !m_bAborted) {

        throw new CFExeption(GetLastError());


    }

}

Solution

  • According MSDN: The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed.

    And, imho, Error 13 is ERROR_INVALID_DATA.