How to append new content in existing text file in Inno Setup

86 Views Asked by At

I have enabled the installation log in Inno Setup using SetupLogging = yes.

It is creating a log file temp directory and I'm copying that log to my program data:

procedure DeinitializeSetup();    
var  
  logfilepathname, newfilepathname: string;  
begin  
  logfilepathname := ExpandConstant('{log}');  
  newfilepathname := 'ProgramData\InstallerlogFile'
 
  FileCopy(logfilepathname, newfilepathname, false);  
end; 

Every time I create a new installer it replaces the content of the older file in program data. I wanted to append new log content instead of replacing it.

1

There are 1 best solutions below

0
Martin Prikryl On BEST ANSWER

The easiest way to append not-too-huge contents from one file to another is using LoadStringFromFile and SaveStringToFile:

var
  S: AnsiString;
begin
  if LoadStringFromFile(logfilepathname, S) then
    SaveStringToFile(newfilepathname, S, True); // True = append
end;

Or you can just execute copy "cmd" command using Exec, when "dest" exists already (if not, use your FileCopy code):

copy [/b] <dest> + <source>

But that won't work for the log, as it is locked by the installer proces. To read a locked file, you need to resort to more low-level functions. You can use TFileStream with its fmShareDenyNone.

For an example, see FileCopyUnrestricted in my answer to
How can I copy the installer to the temp file and then run it?

To make it append, replace the

Stream := TFileStream.Create(NewFile, fmCreate);

with

if not FileExists(NewFile) then Mode := fmCreate
  else Mode := fmOpenWrite;
Stream := TFileStream.Create(NewFile, Mode);
Stream.Seek(0, soFromEnd);
  • Mode is Word variable
  • Once you are using TFileStream, you can optimize the code not to load whole contents to memory at once, in case you need it. You do not, for the log file, as it is not too huge.