How to recursivly delete directory contents without deleting specific subdirectory

StackOverflow https://stackoverflow.com/questions/22957525

  •  30-06-2023
  •  | 
  •  

Вопрос

I am writing an installer/uninstaller in NSIS for my game. My game supports custom mods and I want to give an option whenever delete custom mods during uninstalation or not. Now comes the tricky part: mods are put in subdirectories of $INSTDIR. So if user have some mods to be kept, i want to delete everything beside that submod directory (so I cannot use plain old RMdir /R).

The files I want to keep are of that structure:

$INSTDIR/Modules/[anything-but-Base]
$INSTDIR/Modules/Base/Submod

For example, if user has decided to keep his mods I want to keep directories:

$INSTDIR/Modules/Base/Submod/Sample1
$INSTDIR/Modules/Base/Submod/Sample2
$INSTDIR/Modules/Base/Submod
$INSTDIR/Modules/Sample3
$INSTDIR/Modules/Sample4

And remove everything else from $INSTDIR including empty directories

I've tried to do something like that:

FindFirst $R0 $R1 "$INSTDIR\Modules\Base\*.*"
Loop:
    StrCmp $R1 "" Done
    StrCmp $R1 "Submod" DeleteSubMods
    Goto DeleteCoreMod
    DeleteSubMods:
        RMdir "$INSTDIR/Modules/Base/Submod" ; Remove only if empty
        Goto FindNextItem
    DeleteCoreMod:
        RMdir /R "$INSTDIR/Modules/Base/$R1" ; Remove always
    FindNextItem:
    FindNext $R0 $R1
    Goto Loop
Done:
FindClose $0

RMdir "$INSTDIR/Modules/Base" ; Only if empty
RMdir "$INSTDIR/Modules" ; Only if empty

FindFirst $R0 $R1 "$INSTDIR\*.*"
Loop2:
    StrCmp $R1 "" Done2
    StrCmp $R1 "Modules" FindNextItem2 ; Remove everything but Modules
        RMdir /R "$INSTDIR/$R1"
        Delete "$INSTDIR/$R1"
    FindNextItem2:
    FindNext $R0 $R1
    Goto Loop2
Done2:
FindClose $0

But it's not getting me correct results (it leaves empty $INSTDIR/Modules directory and deletes everything else)

Это было полезно?

Решение 2

There is this: http://nsis.sourceforge.net/Delete_dirs_/_files_in_a_directory_except_one_dir_/_file snippet at NSIS wiki, I was able to adapt it to my own use (forgot about NSIS wiki). Basically the core problems was using interchangeably / and \ by me, and these DO NOT HAVE the same meaning in NSIS

Другие советы

What about deleting only your files?

I suppose during installation you do something like A)

SetOutDir $INSTDIR
File "*.*"

What about creating list of all files one by one B)

SetOutDir $INSTDIR
File "1"
File "2"
File "3"
File "4"
File "n"

In B) case create the same list for uninstaller (in Uninstall section). So only your files will be deleted and mod files remain untouched.

Use RMdir (without /r) to delete directories - they will be deleted only if they are completely empty so your mods will be preserved.

And very last question: isn't it useless to have mods without game? I think they will not work...

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top