Search code examples
conditional-statementsnsis

NSIS FileRead conditional override


I should please need your help as I am not a programmer (please have mercy with me). I should need to add in an existing NSIS script a function that does the following:

Checks the presence of a value called 169.254.1.1 into a INI file named myfile.ini and placed in

c:\mydirectory

Should it find this value into myfile.ini it should not do anything else (i.e. let the script do the next steps).

Should it NOT find this value into myfile.ini it should override the file

with another one by silently copying it from c:\dummyfile\myfile.ini

and then let the script do the next steps.

I do not know how to tell NSIS to do this, may I please ask for your help?

Thanks in advance for your expertise.

Meleena.


Solution

  • If your file is an actual .INI file with [sections] then you can just use the INI functions:

    Section "Prepare INI example"
    InitPluginsDir
    WriteIniStr "$PluginsDir\MyFile.ini" ServerInfo ServerAddress "169.254.1.1"
    WriteIniStr "$PluginsDir\Dummy.ini" ServerInfo ServerAddress "127.0.0.1"
    SectionEnd
    
    !include LogicLib.nsh
    Section
    ReadIniStr $0 "$PluginsDir\MyFile.ini" ServerInfo ServerAddress
    ReadIniStr $1 "$PluginsDir\MyFile.ini" ServerInfo ServerAddressBck
    ${If} $0 != "169.254.1.1"
    ${AndIf} $1 != "169.254.1.1"
        CopyFiles /SILENT /FILESONLY "$PluginsDir\Dummy.ini" "$PluginsDir\MyFile.ini"
    ${EndIf}
    SectionEnd
    

    If you don't have a real .INI file, just a file with name=value pairs then you have to parse manually:

    Section "Prepare fake INI example"
    InitPluginsDir
    FileOpen $0 "$PluginsDir\MyFile.ini" w
    FileWrite $0 'Foo$\r$\n'
    FileWrite $0 'Bar$\r$\n'
    FileWrite $0 'ServerAddress=169.254.1.1$\r$\n'
    FileWrite $0 'Baz$\r$\n'
    FileClose $0
    WriteIniStr "$PluginsDir\Dummy.ini" ServerInfo ServerAddress "127.0.0.1"
    SectionEnd
    
    !include LogicLib.nsh
    
    Function TrimTrailingNewlinesAndSpaces
    Exch $1
    Push $2
    again:
        StrCpy $2 $1 "" -1
        StrCmp $2 " " +3
        StrCmp $2 "$\r" +2
        StrCmp $2 "$\n" +1 +3
        StrCpy $1 $1 -1
        Goto again
    Pop $2
    Exch $1
    FunctionEnd
    
    Section
    StrCpy $2 "" ; Have not found the magic line
    ClearErrors
    FileOpen $0 "$PluginsDir\MyFile.ini" r
    loop:
        FileRead $0 $1
        IfErrors done
        Push $1
        Call TrimTrailingNewlinesAndSpaces
        Pop $1
        ${If} $1 == "ServerAddress=169.254.1.1"
        ${OrIf} $1 == "ServerAddressBck=169.254.1.1"
            StrCpy $2 1
        ${Else}
            Goto loop
        ${EndIf}
    done:
    FileClose $0
    ${If} $2 = 0
        CopyFiles /SILENT /FILESONLY "$PluginsDir\Dummy.ini" "$PluginsDir\MyFile.ini"
    ${EndIf}
    SectionEnd