Delete a folder even if not empty in Windows (C++/MFC)



Following is the code to delete a directory folder even if it is not empty in Windows. Coded in C++/MFC.

 
 
BOOL DeleteFolder(CString strFolder, BOOL bDeleteIfNotEmpty )
{	
	BOOL bRet = FALSE;
	int iRet;
 
	/*NOTE: Why are we creating extra buffer?
	because SHFileOperation is expecting
	extra NULL character at the end*/
 
	if (bDeleteIfNotEmpty)
	{
		SHFILEOPSTRUCT sfo;
		TCHAR *pBuf = NULL;
		CString strWildCardsFolder;
		strWildCardsFolder = strFolder;
		AppendBackslash(strWildCardsFolder);
		strWildCardsFolder += _T("*.*");
 
		//2 for ending NULL characters
		pBuf = new TCHAR[strWildCardsFolder.GetLength()+2];
 
		//extra NULL character
		//memset uses void*, bytes, so we will multiple by sizeof(TCHAR)
		memset(pBuf,0,(strWildCardsFolder.GetLength()+2)*sizeof(TCHAR));
		memcpy(pBuf,strWildCardsFolder,strWildCardsFolder.GetLength()*sizeof(TCHAR));
 
 
		ZeroMemory(&sfo, sizeof(SHFILEOPSTRUCT));
		sfo.hwnd  = NULL;
		//to support both ANSI and UNICODE
		//pFrom expects only Wide characters
		sfo.pFrom = pBuf;
		sfo.pTo = NULL;
		sfo.fFlags = FOF_NO_UI;
		sfo.wFunc = FO_DELETE ;
 
		iRet = SHFileOperation(&sfo);
 
		if (pBuf)
		{
			delete pBuf;
			pBuf = NULL;
		}
	}else
	{
		//if directory is not empty
		if (!PathIsDirectoryEmpty(strFolder))
		{
			return FALSE;
		}
	}
 
	// remove the folder at last
	return RemoveDirectory(GetLongFilePathFormat(strFolder));
 
}


Leave a Reply

Your email address will not be published. Required fields are marked *