1.删除的路径
strPath.Format(L"F:\\RawImage\\Station_%d",1); DeleteFolderTotal(strPath);
2.确定要删除的文件夹是哪些:
void ConfigFileCpyDlg::DeleteFolderTotal(CString cstrDirectoryPath)
{
CFileFind cFinder;
BOOL bFile = cFinder.FindFile(cstrDirectoryPath + L"\\*.*");//查找这个文件夹下有多少个文件夹
bool bNeedRemove = false;
std::vector<CString> vFullName;
while (bFile)
{
bFile = cFinder.FindNextFile();
if (cFinder.IsDots())
{
continue;
}
if (cFinder.IsDirectory())
{
CString strFullName = cFinder.GetFilePath();
vFullName.push_back(strFullName);//每个文件夹的名字放在这个容器vFullName里
}
}
int nSize = (int)vFullName.size();
if (nSize < 100) //文件夹数量<100就不删除了
{
return;
}
nSize = -95;
for (int i = 0; i < nSize; i++)
{
CString strPath = vFullName[i];
gSystemLogger.QueueUpLogAndReport(strPath.GetBuffer(), LV_EVENT);
DeleteDirectory(strPath); //删除排在前面的文件夹及其内部文件
}
}
3.删除目标文件夹及其内部的文件
void ConfigFileCpyDlg::DeleteDirectory(CString strFolder)
{
CString cstrFolderName = strFolder;
CString cstrPath;//文件夹下的文件的路径
CFileFind finder;
//strFolder = L"F:\\RawImage\\JIG_1\\2019-03-21-15-49-35";
cstrPath.Format(L"%s\\*.*", strFolder);//这个是具体的内部文件
strFolder.Append(L"\\");
BOOL bFindFolder = finder.FindFile(cstrPath);
if (!bFindFolder)
{
return;
}
while (bFindFolder)
{
bFindFolder = finder.FindNextFile();
if (finder.IsDots())
{
continue;
}
else
{
CString strFilelName = finder.GetFileName();
CString strFullName = strFolder + strFilelName;
CFile tempFile;
tempFile.Remove(strFullName);//获得文件的名字,然后删除
}
}
RemoveDirectory(cstrFolderName);//全部删除之后,才能删除文件夹,文件夹需要为空才能被删除
}
4.后来发现上文的那个只是删除某个文件夹,假设文件夹内部还有文件夹,就不能正常使用,于是写了递归的算法
bool ConfigFileCpyDlg::DeleteDirectory(CString DirName, BOOL bRemoveRootDir)
{
CFileFind tempFind;
CString csZRootDir;
csZRootDir.Format(L"%s\.", DirName.GetBuffer(0));
BOOL IsFinded = (BOOL)tempFind.FindFile(csZRootDir.GetBuffer(0));
while (IsFinded)
{
IsFinded = (BOOL)tempFind.FindNextFile();
if (!tempFind.IsDots())
{
CString csFileName;
csFileName.Format(L"%s", tempFind.GetFileName().GetBuffer(0));
if (tempFind.IsDirectory())
{
CString tmp;
tmp.Format(L"%s\\%s", DirName.GetBuffer(0), csFileName.GetBuffer(0));
DeleteDirectory(tmp, TRUE);
}
else
{
CString tmp;
tmp.Format(L"%s\\%s", DirName, csFileName.GetBuffer(0));
DeleteFile(tmp.GetBuffer(0));
}
}
}
tempFind.Close();
if (bRemoveRootDir)
{
if (!RemoveDirectory(DirName))
{
return FALSE;
}
}
return TRUE;
}
函数的标记位参数就是用于删除选定的文件夹