inno-setuppascalscript

How can I copy the installer to the temp file and then run it?


I am trying to copy the installer to the temp folder and then run it from that location.

This is what I am trying to do, but so far to no avail.

FileCopy(ExpandConstant('{srcexe}'), ExpandConstant('{tmp}\Setup.exe'), True);
Exec(ExpandConstant('{tmp}\Setup.exe'), '', '', SW_SHOW, ewWaitUntilTerminated, ResultCode)

How can I copy the installer to the temp file and then run it from the code section?


Solution

  • No idea why, but there's an explicit check that prevents CopyFile function from copying the installer itself. In 6.4.0 the protection was somewhat limited. Now it is possible to copy the installer once the installation starts. The documentation says:

    Can't be used to copy Setup itself until the installation has started.

    I do not know what is the reason for this, but there probably is some. So beware, you might be doing something that the installer does not like.


    You can of course workaround that by calling Windows copy command:

    Exec(
      ExpandConstant('{cmd}'),
      Format('/C copy "%s" "%s"', [ExpandConstant('{srcexe}'), ExpandConstant('{tmp}\Setup.exe')]),
      '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
    

    Or you can implement a replacement function with use of TFileStream class:

    function FileCopyUnrestricted(const ExistingFile, NewFile: String): Boolean;
    var
      Buffer: string;
      Stream: TFileStream;
      Size: Integer;
    begin
      Result := True;
      try
        Stream := TFileStream.Create(ExistingFile, fmOpenRead or fmShareDenyNone);
        try
          Size := Stream.Size;
          SetLength(Buffer, Size div 2 + 1);
          Stream.ReadBuffer(Buffer, Size);
        finally
          Stream.Free;
        end;
      except
        Result := False;
      end;
    
      if Result then
      begin
        try
          Stream := TFileStream.Create(NewFile, fmCreate);
          try
            Stream.WriteBuffer(Buffer, Size);
          finally
            Stream.Free;
          end;
        except
          Result := False;
        end;
      end;
    end;
    

    This is an inefficient implementation that loads whole file to memory. If your installer is large, you will have to improve the code to copy the file in chunks.

    The code is for Unicode version of Inno Setup (the only version as of Inno Setup 6).

    FileCopy has been renamed to CopyFile in 6.4.0.