Monday, December 15, 2008

[VC++] Recursive folder deletion by SHFileOperation

If you have a requirment to delete a folder, you may go first and give a try with API RemoveDirectory(). And you may not be happy with the fact that RemoveDirectory() deletes only an empty directory. The RemoveDirectory() marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed. If you want to delete a directory with RemoveDirectory(), you may need to delete the folder contents recursively each level inside the
folder to be deleted. If you come up with such a situation to delete a folder and all its contents don't spend your time with recursive logic, go for shell function SHFileOperation() with which you can Copy, move, rename, or delete a file system object. For Deleting the folder (which is not empty), below function can be used.

// csDeleteFolderPath_i - Path of the folder to be deleted
bool DeleteFolder( const CString& csDeleteFolderPath_i )
{
// Making the directory name double null terminated
int nFolderPathLen = csDeleteFolderPath_i.GetLength();
TCHAR *pszFrom = new TCHAR[nFolderPathLen + 2];
_tcscpy(pszFrom, csDeleteFolderPath_i);
pszFrom[nFolderPathLen] = 0;
pszFrom[++nFolderPathLen] = 0;
SHFILEOPSTRUCT stSHFileOpStruct = {0};

// Delete operation
stSHFileOpStruct.wFunc = FO_DELETE;
// Folder name as double null terminated string
stSHFileOpStruct.pFrom = pszFrom;
// Do not prompt the user
stSHFileOpStruct.fFlags = FOF_NOCONFIRMATIONFOF_SILENT;
// Delete operation can be undo (to recycle bin)
stSHFileOpStruct.fFlags = FOF_ALLOWUNDO;
//Check for any operation is aborted
stSHFileOpStruct.fAnyOperationsAborted = FALSE;
int nFileDeleteOprnRet = SHFileOperation( &stSHFileOpStruct );
delete []pszFrom;
if( 0 != nFileDeleteOprnRet )
{
// Failed deletion
return false;
}
// Deletion was successfull
return true;
}

Please note that you can customize the file operation with a numerous options set to SHFILEOPSTRUCT object which inturn pass to the SHFileOperation().




3 comments:

Anonymous said...

Thanks Buddy,
I just can't understand how you people so cool to post such useful things. It makes life lot esier for other guys like me.

Anonymous said...

Very useful! Thank you.

Anonymous said...

Exactly. Thank you. :D