Search code examples
inno-setuppascalscript

Call Inno Setup AfterInstall function only when the file is not skipped due to onlyifdoesntexist flag


AfterInstall function is always called, even if file already exists :

[Files]
Source: "myfile.txt"; DestDir: "{app}"; Flags: onlyifdoesntexist; \
    AfterInstall: MyAfterInstall('{app}\myfile.txt')

In case "myfile.txt" already exists, it is not overwritten (not installed) and AfterInstall should not be called in this case (in my opinion).


Solution

  • You can use Check parameter instead of onlyifdoesntexist flag.

    [Files]
    Source: "MyProg.exe"; DestDir: "{app}"; Check: OnlyIfDoesntExist; \
        AfterInstall: MyAfterInstall
    
    [Code]
    
    function OnlyIfDoesntExist: Boolean;
    var
      FileName: string;
    begin
      FileName := ExpandConstant(CurrentFilename);
      Result := not FileExists(FileName);
      if Result then
      begin
        Log(Format('Installing "%s" as the file does not exists yet.', [FileName]));
      end
        else
      begin
        Log(Format('Skipping "%s" as the files exists already.', [FileName]));
      end;
    end;
    
    procedure MyAfterInstall;
    begin
      Log(Format('Installed "%s".', [ExpandConstant(CurrentFilename)]));
    end;
    

    Note that the Check function is called several times, so you will see the respective message several times in the log. If you happen to turn the check to an expensive function, you better cache the results.

    Also note above that you do not have to pass a file name to your AfterInstall procedure, as you can retrieve the name using CurrentFilename function.