fixed bug when clearing directories

Modifying the directory contents while enumerating caused problems with
skipped files. Added a fix to store the enumerated files in a list first.