28. How do I delete a directory tree that isn't empty?
You can't use RemoveDirectory, because it only works on
empty directories/folders. But you CAN use a Shell function for this, the ubiquitous
SHFileOperation :
SHFILEOPSTRUCT sh;
sh.hwnd = GetSafeHwnd();
sh.wFunc = FO_DELETE;
sh.pFrom = "c:\\test\0";
sh.pTo = NULL;
sh.fFlags = FOF_NOCONFIRMATION | FOF_SILENT;
sh.hNameMappings = 0;
sh.lpszProgressTitle = NULL;
SHFileOperation (&sh);
That code will softly and silently remove an entire tree,
starting from (and including) c:\test.
NOTE : under NT, this may fail because a
process has a folder or subfolder as its current directory. This problem does
not arise in Win9x.
~ Extra Wrinkle ~
This comes courtesy of Ed Eichman, who wrote to tell me about a problem he
had with removing a folder tree:
I had a "remove dir" function that removed all files in the dir, and then deleted the dir itself. I used CFileFind to get and delete the files,
and then called _rmdir WITHOUT FIRST CALLING CFileFind.Close ()!
Adding the Close fixed my problem.