Search code examples
inno-setuppascalscript

how to modify the exe.config from Innosetup script


I've started to learn Innosetup scripting by myself. For this i have created a simple C# console application, which reads an element from a configuration file and outputs onto the console.

<configuration>
  <appSettings>
    <add key ="Name" value="Brad Pitt"/> 
  </appSettings>
</configuration>

For ex: It shall read the value by querying the key attribute "Name".

I want the value in the .config to be written from the Innosetup setup script.

i.e During the installation process i shall gather the name (i.e "Brad Pitt" in this case) and write it to the value of the config file

<add key ="Name" value="Brad Pitt"/> 

Question is how do i achieve this, using a Pascal script or a standard script.

Any guidance is deeply appreciated

Regards

VATSA


Solution

  • To achieve this I created a simple procedure, which takes the xml file name as input. The procedure shall parse each line and write the contents to a temp file. The code checks each line looking for the string 'key="Name"':

       if (Pos('key="Name"', strTest) <> 0 ) 
    

    If it finds a match then I replace that particular line by my desired tag, of which the value is gotten from my custom page.

       strTest := '  <add key="Name" value="' + strName + '"/> ';
    

    This gets written into a temp file. I then delete the original exe.config file and rename the temp config file to the exe.config file (thus reflecting the changes I need). Below is the entire code snippet for the procedure, and don't forget to call the procedure from [Files] i.e.

    [Files]
    Source: "HUS.exe.config"; DestDir: "{app}"; AfterInstall: ConvertConfig('HUS.exe.config')
    

    Code Snippet

    procedure ConvertConfig(xmlFileName: String);
    var
      xmlFile: String;
      xmlInhalt: TArrayOfString;
      strName: String;
      strTest: String;
      tmpConfigFile: String;
      k: Integer;
    begin
      xmlFile := ExpandConstant('{app}') + '\' + xmlFileName;
      tmpConfigFile:= ExpandConstant('{app}') + '\config.tmp';
      strName :=  UserPage.Values[0] +' '+ UserPage.Values[1];
    
      if (FileExists(xmlFile)) then begin
        // Load the file to a String array
        LoadStringsFromFile(xmlFile, xmlInhalt);
    
        for k:=0 to GetArrayLength(xmlInhalt)-1 do begin
          strTest := xmlInhalt[k];
          if (Pos('key="Name"', strTest) <> 0 ) then  begin
            strTest := '  <add key="Name" value="' + strName + '"/> ';
          end;
          SaveStringToFile(tmpConfigFile, strTest + #13#10,  True);
        end;
    
        DeleteFile(xmlFile); //delete the old exe.config
        RenameFile(tmpConfigFile,xmlFile);
      end;
    end;