MFC_选择目录对话框_选择文件对话框_指定目录遍历文件

时间:2023-03-09 03:47:41
MFC_选择目录对话框_选择文件对话框_指定目录遍历文件

选择目录对话框

void C资源共享吧视频广告清理工具Dlg::OnBnClickedCls()
{
// 清空编辑框内容
m_Edit.SetWindowTextW(L"");
m_Edit2.SetWindowTextW(L"");
// 打开一个文件夹选择对话框(选择目录)
CFolderPickerDialog dlg;
// 设置对话框标题
dlg.m_ofn.lpstrTitle = TEXT("请选择清理目录");
// 点击了选择文件夹才去清理垃圾
if (dlg.DoModal() == TRUE)
{
// 获取选则的目录
CString path = dlg.GetFolderPath();
// 设置编辑框内容(m_Edit 是 CEdit 类型)
m_Edit.SetWindowTextW(path);
// 清理广告
ClsAd(path);
}
else
{
::MessageBox(, L"请选择清理目录!", L"提示", );
}
}

选择文件对话框

// 1、打开一个文件夹选择对话框
CFileDialog dlg(TRUE);
if (dlg.DoModal() == IDOK)
{
CString path = dlg.GetFolderPath();
// 2、获取选择的文件的后缀名,判断是否是DLL
CString path1 = dlg.GetFileName();
PCTSTR FileType = PathFindExtension(path1);
if (wcscmp(FileType, L".dll") != )
{
m_Edit2.SetWindowText(L"");
return;
}
// 3、将文件路径显示到编辑框
m_Edit2.SetWindowText(path + L"\\" + path1);
}

指定目录遍历文件

void C资源共享吧视频广告清理工具Dlg::ClsAd(const CString path)
{
// 调用FindFirstFile找到这个目录下的第一个文件/文件夹
WIN32_FIND_DATA fData = { };
HANDLE hFind = FindFirstFile(path + "\\*", &fData);
if (hFind == INVALID_HANDLE_VALUE)
{
::MessageBox(, L"查找文件失败!", L"提示", );
return;
}
// 再循环调用FindNextFile得到后续所有的文件/文件夹
do
{
CString strName(fData.cFileName);
// 过滤掉当前目录和上一级目录
if (wcscmp(fData.cFileName, L".") == || wcscmp(fData.cFileName, L"..") == )
{
continue;
}
// 查找广告文件删除
if (wcscmp(fData.cFileName, L"本教程由资源共享吧提供.url") == || wcscmp(fData.cFileName, L"下载必看.txt") == || wcscmp(fData.cFileName, L"更多精品教程.url") == )
{
CString strText = _T("");
// 获取编辑框2当前文本
m_Edit2.GetWindowTextW(strText);
// 拼接字符串
strText += path + L"\\" + strName + L"已删除!\r\n";
// 设置编辑框2文本
m_Edit2.SetWindowTextW(strText);
// 删除文件
DeleteFile(path + L"\\" + strName);
}
// 如果文件是一个文件夹的话, 就递归遍历
if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
ClsAd(path + L"\\" + strName);
}
} while (FindNextFile(hFind, &fData));
}

相关文章