Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Inno Setup scripting to insert lines into a text file?

Objective is to insert multiple lines (once) at beginning of text document.

But I have been having problems with the approaches I found. I've attempted to adjust them but it incorporates side-effect issues.

Two problems:

  1. Appends end of file instead of inserting into line locations.
  2. In its present design, it appends the file 3 times.

In reference to the other scripts I found both lines incorporating Result := resulted in unknown identifier.

References:

  • How to use Inno Setup scripting to append to a text file?

  • https://www.codeproject.com/Questions/477984/createplusandpluswriteplusbatchplusfileplusinplusi

[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
  ErrorCode: Integer;
  FileName: string;
  lines : TArrayOfString;
begin
  fileName := ExpandConstant('{userappdata}\xy');
  fileName := AddBackslash(FileName) + 'zlt.net';
  SetArrayLength(lines, 6); 
  lines[0] := 'A';
  lines[1] := 'B';
  lines[2] := 'C';
  lines[3] := 'D';
  lines[4] := 'E';
  lines[5] := 'F';
  SaveStringsToFile(filename,lines,true);
end;
like image 520
Jenn Avatar asked Oct 17 '25 09:10

Jenn


1 Answers

  1. There's no way to insert lines into file. You have to recreate whole file.

  2. CurStepChanged is triggered for every step of the installation. You will want to insert the lines in one of the steps only (likely ssInstall or ssPostInstall)

procedure CurStepChanged(CurStep: TSetupStep);
var
  Lines: TStringList;
begin
  if CurStep = ssPostInstall then
  begin
    Lines := TStringList.Create;
    try
      Lines.LoadFromFile(FileName);

      Lines.Insert(0, 'A');
      Lines.Insert(1, 'B');
      Lines.Insert(2, 'C');
      Lines.Insert(3, 'D');
      Lines.Insert(4, 'E');
      Lines.Insert(5, 'F');

      Lines.SaveToFile(FileName);
    finally
      Lines.Free;
    end;
  end;
end;

The code loads whole file to memory. That can be a problem if the file is too large. But that should not be a problem for files smaller than tens of MBs. Also repeatedly calling Insert is not efficient. But for small files and few lines, this should not be a problem either.

like image 133
Martin Prikryl Avatar answered Oct 20 '25 04:10

Martin Prikryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!