This project has moved. For the latest updates, please go here.

Algorithm or Strategy employed

To be able to delete all folders and their content, without attempting to delete a parent folder before deleting its children elements, I know two different possible approaches:
  • Use a recursive function that goes deep first, on folders, then breadth, on delete files, return to caller and have folder removed. Repeat for all children folders.
  • Use a stack (LIFO list) to push folders in while traversing the folders tree, delete files as found. While there are items in the stack, pop folder, get all children files and delete, if any folders push curent and push all children.
I decided on the stack, mostly because of performance and fear to run out of heap space for the recursive calls.

Here is the algorithm in pseudo code:
   stack.push( targetFolder)
   while( stack.HasItems)
   {
      childrenFolderFound <-- FALSE
      currentFolder <-- stack.pop
      for each( file in getFiles( currentFolder))
      {
         if (file is FOLDER)
         {
            if( NOT childrenFolderFound)
            {
               childrenFolderFound <-- TRUE
               stack.push( currentFolder)
            }
            stack.push( file)
         }
         else
         {
            delete( file)
         }
      }
      if( NOT childrenFolderFound)
      {
         remove( currentFolder)
      }
   }

Gotchas

  • You have to ignore the '.' and '..' folders.
  • To be able to delete de file, you have to remove the READONLY, HIDDEN and SYSTEM file attributes or set file to Normal attribute. Because you are removing all files, it makes no difference to change some of the file attributes to be able to delete them.
  • After you succesfully remove a folder you have to wait until all open handles on the folder are released to be sure you won't find the folder in the next loop. That's the reason why there is a wait loop after the app 'succesfully' removes a folder. Also, because I couldn't find any doc stating that when you delete a file all handles are automatically closed, I decided to play safe on files too and added the wait loop on them.
  • In order to be able to cope with paths longer than 260 characters, you have to use the Unicode interface of the Kernel32 calls. Those interfaces are clearly identified by the 'W' suffix; you see, it's Über Unicode so it has to be written with a double U ;-) !!

Kernel32 calls

Last edited Apr 29, 2011 at 10:41 PM by JPJofre, version 14

Comments

No comments yet.