Archive: Recursive Delete all SUBdirs and Files


Recursive Delete all SUBdirs and Files
Hi,

I tested RMDIR /r and Delete. How can I delete all files and subdirectories but the specified (main) directory.

RMDIR /r "$INSTDIR" removes all files and subdirs inclusive $INSTDIR.

I want to remove all files and subdirs exclusive $INSTDIR.

Delete "$INSTDIR\*.*" removes all files but no subdirectories.


Two steps:
RMDIR /r "$INSTDIR"
CreateDirectory $INSTDIR
;)


:( No, Sorry, this is exactly I want to avoid! I wrote quite some code to pass the directory from installer to uninstaller to leave the start menu group folder intact.

I don't want this folder to be erased by the uninstaller and created by the installer because WinXP (Luna) shows the folder as new. Additionally any user sort order gets lost. I want to avoid this.

So I need the main folder to persist all the time.


You can use Delete * for files first and FindFirst/Next with RmDir for directories. NSIS help, 4.9.5.9 or use forum search.


You're right. I did some more testing with RMDir/Delete but it seems impossible without extra coding. I will implement Find[First|Next] now...


Solution


!macro RemoveFilesAndSubDirs DIRECTORY
!define Index_RemoveFilesAndSubDirs 'RemoveFilesAndSubDirs_{__LINE__}'

Push $0
Push $1
Push $2

StrCpy $2 "${DIRECTORY}"
FindFirst $0 $1 "$2*.*"
${Index_RemoveFilesAndSubDirs}-loop:
StrCmp $1 "" ${Index_RemoveFilesAndSubDirs}-done
StrCmp $1 "." ${Index_RemoveFilesAndSubDirs}-next
StrCmp $1 ".." ${Index_RemoveFilesAndSubDirs}-next
IfFileExists "$2$1\*.*" ${Index_RemoveFilesAndSubDirs}-directory
; file
Delete "$2$1"
goto ${Index_RemoveFilesAndSubDirs}-next
${Index_RemoveFilesAndSubDirs}-directory:
; directory
RMDir /r "$2$1"
${Index_RemoveFilesAndSubDirs}-next:
FindNext $0 $1
Goto ${Index_RemoveFilesAndSubDirs}-loop
${Index_RemoveFilesAndSubDirs}-done:

FindClose $0

Pop $2
Pop $1
Pop $0
!undef Index_RemoveFilesAndSubDirs
!macroend