//CreateDirectoryTree
DWORD CreateDirectoryTree(CString cstrNewDir, LPSECURITY_ATTRIBUTES lpSecurityAttributes)
{
DWORD dwRetVal = 0;
int iIndex, iStart = 0;
CString cstrActPath, cstrLastExisting, cstrFirstCreated;
cstrNewDir.TrimRight('\\');
iIndex = cstrNewDir.Find('\\');
while(iIndex != -1)
{
cstrActPath = cstrNewDir.Left(iIndex);
if(!PathFileExists(cstrActPath))
{
if(!CreateDirectory(cstrActPath, lpSecurityAttributes))
{
dwRetVal = GetLastError();
if(!cstrFirstCreated.IsEmpty())
{
RemoveDirectoryTree(cstrLastExisting, cstrFirstCreated);
}
break;
}
else if(cstrFirstCreated.IsEmpty())
cstrFirstCreated = cstrActPath.Mid(cstrActPath.ReverseFind('\\'));
}
else
cstrLastExisting = cstrActPath;
iStart = iIndex + 1;
iIndex = cstrNewDir.Find('\\', iIndex + 1);
}
if(dwRetVal == 0)
{
cstrActPath = cstrNewDir;
if(!PathFileExists(cstrActPath))
{
if(!CreateDirectory(cstrActPath, lpSecurityAttributes))
{
dwRetVal = GetLastError();
if(!cstrFirstCreated.IsEmpty())
{
RemoveDirectoryTree(cstrLastExisting, cstrFirstCreated);
}
}
}
else
cstrLastExisting = cstrActPath;
}
return dwRetVal;
}
//RemoveDirectoryTree
DWORD RemoveDirectoryTree(CString cstrBaseDir, CString cstrRemoveDir)
{
DWORD dwRetVal = 0;
BOOL bOK;
CString cstrActPath, cstrSearch, cstrFileName;
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
if(cstrBaseDir.Right(1) != "\\")
cstrBaseDir += '\\';
cstrRemoveDir.TrimRight('\\');
cstrRemoveDir.TrimLeft('\\');
cstrActPath = cstrBaseDir + cstrRemoveDir;
if(!PathFileExists(cstrActPath))
{
return ERROR_PATH_NOT_FOUND;
}
cstrSearch = cstrActPath + "\\*";
hFind = FindFirstFile(cstrSearch, &FindFileData);
if(hFind != INVALID_HANDLE_VALUE)
{
cstrFileName = FindFileData.cFileName;
if((cstrFileName != ".") && (cstrFileName != ".."))
{
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
RemoveDirectoryTree(cstrActPath, FindFileData.cFileName);
}
else
{
::DeleteFile(FindFileData.cFileName);
}
}
while(FindNextFile(hFind, &FindFileData))
{
cstrFileName = FindFileData.cFileName;
if((cstrFileName != ".") && (cstrFileName != ".."))
{
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
RemoveDirectoryTree(cstrActPath, FindFileData.cFileName);
}
else
{
::DeleteFile(FindFileData.cFileName);
}
}
}
FindClose(hFind);
}
bOK = RemoveDirectory(cstrActPath);
if(!bOK)
{
dwRetVal = GetLastError();
}
return dwRetVal;
}