Dielo
Dielo

Reputation: 623

Inno Setup - How to edit a specific line from a text file during setup?

I need to edit a specific line from a text file using Inno Setup. I need my installer to find this line ("appinstalldir" "C:MYXFOLDER\\apps\\common\\App70") and use the directory path from the installer.

This is the code I am trying to use:

procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep = ssDone then
  begin
    SaveStringToFile(
      ExpandConstant('{app}\app70.txt'),
      'directory's path' + '\\apps\\common\\App70', True);
  end;
end;

This is my text file:

"App"
{
    "appID"     "70"

    {
        "appinstalldir"     "C:MYXFOLDER\\apps\\common\\App70"
    }
}

Upvotes: 4

Views: 10204

Answers (1)

TLama
TLama

Reputation: 76693

This code can do it. But note, that this code doesn't check, if the value for the tag is enclosed by quote chars, once it finds a tag specified by TagName parameter, it cuts off the rest of the line and appends the value given by TagValue parameter:

function ReplaceValue(const FileName, TagName, TagValue: string): Boolean;
var
  I: Integer;
  Tag: string;
  Line: string;
  TagPos: Integer;
  FileLines: TStringList;
begin
  Result := False;
  FileLines := TStringList.Create;
  try
    Tag := '"' + TagName + '"';
    FileLines.LoadFromFile(FileName);
    for I := 0 to FileLines.Count - 1 do
    begin
      Line := FileLines[I];
      TagPos := Pos(Tag, Line);
      if TagPos > 0 then
      begin
        Result := True;
        Delete(Line, TagPos + Length(Tag), MaxInt);
        Line := Line + ' "' + TagValue + '"';
        FileLines[I] := Line;
        FileLines.SaveToFile(FileName);
        Break;
      end;
    end;
  finally
    FileLines.Free;
  end;
end;

procedure CurStepChanged(CurStep: TSetupStep);
var
  NewPath: string;
begin
  if CurStep = ssDone then
  begin
    NewPath := ExpandConstant('{app}') + '\apps\common\App70';
    StringChangeEx(NewPath, '\', '\\', True);

    if ReplaceValue(ExpandConstant('{app}\app70.txt'), 'appinstalldir', 
      NewPath) 
    then
      MsgBox('Tag value has been replaced!', mbInformation, MB_OK)
    else  
      MsgBox('Tag value has not been replaced!.', mbError, MB_OK);
  end;
end;

Upvotes: 9

Related Questions