Why is RemoveDirectory function not deleting the top most folder?

后端 未结 3 1142
故里飘歌
故里飘歌 2020-12-18 12:11

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

相关标签:
3条回答
  • 2020-12-18 12:20

    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.

    0 讨论(0)
  • 2020-12-18 12:32

    Refer:http://www.codeguru.com/forum/archive/index.php/t-337897.html
    Given below is the code to delete directory using SHFileOperation

    bool DeleteDirectory(LPCTSTR lpszDir, bool noRecycleBin = true)
    {
        int len = _tcslen(lpszDir);
        TCHAR* pszFrom = new TCHAR[len+4]; //4 to handle wide char
        //_tcscpy(pszFrom, lpszDir); //todo:remove warning//;//convet wchar to char*
        wcscpy_s (pszFrom, len+2, lpszDir);
        pszFrom[len] = 0;
        pszFrom[len+1] = 0;
    
        SHFILEOPSTRUCT fileop;
        fileop.hwnd   = NULL;    // no status display
        fileop.wFunc  = FO_DELETE;  // delete operation
        fileop.pFrom  = pszFrom;  // source file name as double null terminated string
        fileop.pTo    = NULL;    // no destination needed
        fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT;  // do not prompt the user
    
        if(!noRecycleBin)
            fileop.fFlags |= FOF_ALLOWUNDO;
    
        fileop.fAnyOperationsAborted = FALSE;
        fileop.lpszProgressTitle     = NULL;
        fileop.hNameMappings         = NULL;
    
        int ret = SHFileOperation(&fileop); //SHFileOperation returns zero if successful; otherwise nonzero 
        delete [] pszFrom;  
        return (0 == ret);
    }
    
    0 讨论(0)
  • 2020-12-18 12:40

    I believe you have to close the file handle before the recursive call. Which means after exiting the recursive call you must again set your your file handle to something appropriate.

    SHFileOperation may be a better solution; I am just answering the OP's question of why their code wasn't working as intended.

    0 讨论(0)
提交回复
热议问题