在开发“518抽奖软件”的时候,每次导入一批新图片的时候,要删除原来的图片文件夹。 本来递归删除即可,应该很快速的,但是在windows 10下发现删除很慢,软件会卡在那里,因为windows 10的安全性,里面很多智能的检查。 软件卡在那里总不行的,只能rename文件夹后,创建一个线程慢慢删除那个文件夹,请参看下面源码。
Windows 10 下删除文件夹及里面的文件源码
void Tfuns::del_folder (const WCHAR* folder)
{
if (*folder == 0) return; //!!
WCHAR suffix[64] = { 0 };
WCHAR tmpFolder[MAX_PATH] = { 0 };
int len = wcslen(folder);
//rename后的临时文件夹的名字
int seqno = 1;
GET_TMPFOLDER:
wcscpy(tmpFolder, folder);
if (tmpFolder[len - 1] == L'\\' || tmpFolder[len - 1] == L'/')
tmpFolder[len - 1] = 0;
swprintf(suffix, L"_toDel%d", seqno);
wcscat(tmpFolder, suffix);
if (PathFileExists(tmpFolder)) {
seqno++;
goto GET_TMPFOLDER;
}
if (_wrename(folder, tmpFolder) == 0)
{
wstring* p = new wstring(tmpFolder); //!! 必须的,线程传递参数
HANDLE h = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Thread_delFolderW, (LPVOID)p, 0, 0);
CloseHandle(h);
}
}
static DWORD WINAPI Thread_delFolderW(LPVOID lpParameter)
{
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
setlocale(LC_ALL, "");
recursive_del(((wstring*)lpParameter)->c_str());
delete ((wstring*)lpParameter);
return 0;
}
static void recursive_del(const WCHAR* folder)
{
WCHAR srch[MAX_PATH] = { 0 };
WIN32_FIND_DATA wfd = { 0 };
PathCombine(srch, folder, L"*.*");
HANDLE h = FindFirstFile(srch, &wfd);
if (h == INVALID_HANDLE_VALUE)
return;
while (1)
{
WCHAR file[MAX_PATH] = { 0 };
PathCombine(file, folder, wfd.cFileName);
if (wcscmp(wfd.cFileName, L".") == 0) { ; }
else if (wcscmp(wfd.cFileName, L"..") == 0) { ; }
else if (PathIsDirectory(file)) recursive_del(file);
else {
SetFileAttributes(file, FILE_ATTRIBUTE_NORMAL);
DeleteFile(file);
}
if (!FindNextFile(h, &wfd)) break;
}
FindClose(h);
SetFileAttributes(folder, FILE_ATTRIBUTE_NORMAL);
RemoveDirectory(folder);
}