Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 569
user1967718 Avatar asked Oct 20 '25 15:10

user1967718


1 Answers

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
like image 60
Anders Avatar answered Oct 23 '25 14:10

Anders