1. 程式人生 > >vc中刪除資料夾以及資料夾中的內容的三種方法

vc中刪除資料夾以及資料夾中的內容的三種方法

BOOL CDeleteFolderDlg::DeleteFolder(CString lpszPath)//刪除資料夾以及資料夾內的檔案

CHAR szFromPath[_MAX_PATH];//原始檔路徑
memcpy(szFromPath, lpszPath, lpszPath.GetLength());
szFromPath[lpszPath.GetLength() + 1] = '\0';//必須要以“\0\0”結尾,不然刪除不了
szFromPath[lpszPath.GetLength() + 2] = '\0';


SHFILEOPSTRUCT FileOp; 
SecureZeroMemory((void*)&FileOp, sizeof(SHFILEOPSTRUCT));
//secureZeroMemory和ZeroMerory的區別
//根據MSDN上,ZeryMerory在當緩衝區的字串超出生命週期的時候,
//會被編譯器優化,從而緩衝區的內容會被惡意軟體捕捉到。
//引起軟體安全問題,特別是對於密碼這些比較敏感的資訊而說。
//而SecureZeroMemory則不會引發此問題,保證緩衝區的內容會被正確的清零。
//如果涉及到比較敏感的內容,儘量使用SecureZeroMemory函式。


FileOp.fFlags = FOF_NOCONFIRMATION;//操作與確認標誌 
FileOp.hNameMappings = NULL;//檔案對映 
FileOp.hwnd = NULL;//訊息傳送的視窗控制代碼;
FileOp.lpszProgressTitle = NULL;//檔案操作進度視窗標題 
FileOp.pFrom = szFromPath;//原始檔及路徑 
FileOp.pTo = NULL;//目標檔案及路徑 
FileOp.wFunc = FO_DELETE;//操作型別 


return SHFileOperation(&FileOp) == 0;
}


bool  CDeleteFolderDlg::DeleteDirectory(CString DirName)
{
//AfxMessageBox("執行刪除資料夾:" + DirName);
CString PUBPATH;
PUBPATH = DirName;
CFileFind tempFind;
DirName += "\\*.*";
BOOL IsFinded = (BOOL)tempFind.FindFile(DirName);
while(IsFinded)
{
IsFinded = (BOOL)tempFind.FindNextFile();
if(!tempFind.IsDots())
{
CString strDirName;
strDirName += PUBPATH;
strDirName += "\\";
strDirName += tempFind.GetFileName();
//AfxMessageBox("strDirName :" + strDirName);
if(tempFind.IsDirectory())
{
//strDirName += PUBPATH;
DeleteDirectory(strDirName);
}
else
{
SetFileAttributes(strDirName, FILE_ATTRIBUTE_NORMAL); //去掉檔案的系統和隱藏屬性
DeleteFile(strDirName);
}
}
}
tempFind.Close();
if(!RemoveDirectory(PUBPATH))
{
return false ;
}
//AfxMessageBox("資料夾刪除成功...");
return true;
}


//方法二
bool  CDeleteFolderDlg::DeleteDirectory( char* DirName)
{
HANDLE hFirstFile = NULL; 
WIN32_FIND_DATA FindData; 


char currdir[MAX_PATH] = {0};
sprintf_s(currdir, "%s\\*.*", DirName);


hFirstFile = ::FindFirstFile(currdir, &FindData); 
if( hFirstFile == INVALID_HANDLE_VALUE ) 
return false;


BOOL bRes = true;


while(bRes) 

bRes = ::FindNextFile(hFirstFile, &FindData);


if( (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) //發現目錄
{
if( !strcmp(FindData.cFileName, ".") || !strcmp(FindData.cFileName, "..") ) //.或..
continue;
else
{
char tmppath[MAX_PATH] = {0};
sprintf_s(tmppath, "%s\\%s", DirName, FindData.cFileName);


DeleteDirectory(tmppath);
}
}
else               //發現檔案
{
char tmppath[MAX_PATH] = {0};
sprintf_s(tmppath, "%s\\%s", DirName, FindData.cFileName);
::DeleteFile(tmppath);    
}

::FindClose(hFirstFile);
if(!RemoveDirectory(DirName))
{
return false ;
}
return true;
}