简体   繁体   中英

NSIS, detect if directory exists during installation

I have installer, which supports choosing installation directory. And I want to detect if given folder exists and if it is empty. If it is NOT empty, show warning message box, then remove all its contents and install program into that folder. Only problem is to get into the right code section, where I can get installation folder given by user during installation, I can handle the rest.

Thank you for any advices.

Normally you would just check if the directory exists:

Outfile "$%Temp%\Test.exe"
RequestExecutionLevel user
InstallDir "$Documents\Test"

!include LogicLib.nsh

Page Directory "" "" DirLeave
Page InstFiles

Function DirLeave
${If} ${FileExists} "$InstDir\*"
    MessageBox MB_YESNO `"$InstDir" already exists, delete it's content and continue installing?` IDYES yep
    Abort
yep:
    RMDir /r "$InstDir"
${EndIf}
FunctionEnd

Section
SetOutPath $InstDir
File myfile.ext
SectionEnd

This will also display the message if the directory exists but is empty. To work around that you would need some custom detection:

!macro _IsNonEmptyDirectory _a _b _t _f
!insertmacro _LOGICLIB_TEMP
!insertmacro _IncreaseCounter
Push $0
FindFirst $0 $_LOGICLIB_TEMP "${_b}\*"
_IsNonEmptyDirectory_loop${LOGICLIB_COUNTER}:
    StrCmp "" $_LOGICLIB_TEMP _IsNonEmptyDirectory_done${LOGICLIB_COUNTER}
    StrCmp "." $_LOGICLIB_TEMP +2
    StrCmp ".." $_LOGICLIB_TEMP 0 _IsNonEmptyDirectory_done${LOGICLIB_COUNTER}
    FindNext $0 $_LOGICLIB_TEMP
    Goto _IsNonEmptyDirectory_loop${LOGICLIB_COUNTER}
_IsNonEmptyDirectory_done${LOGICLIB_COUNTER}:
FindClose $0
Pop $0
!insertmacro _!= "" $_LOGICLIB_TEMP `${_t}` `${_f}`
!macroend
!define IsNonEmptyDirectory `"" IsNonEmptyDirectory`

Function DirLeave
${If} ${IsNonEmptyDirectory} "$InstDir"
    MessageBox MB_YESNO `"$InstDir" already exists, delete it's content and continue installing?` IDYES yep
    Abort
yep:
    RMDir /r "$InstDir"
${EndIf}
FunctionEnd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM