How to rename a file using inno setup

2019-07-02 20:59发布

问题:

I want to first rename an existing file 'My program old' to 'My program v2' but only if 'My program v2' doesn't already exist.

Then I want to rename 'My program' to 'My program old' but only if 'My program old' doesn't already exist.

And then I want to install 'My program' from the installer but only if 'My program' doesn't already exist.

I would be very grateful for any guidance !

回答1:

I would give a try to something like this. In the ssInstall stage of the CurStepChanged event, which occurs just before the installation process starts, just check if the file doesn't exist with the FileExists function, and if not, then just call the RenameFile function, which will silently fail if the source file doesn't exist, so you don't need to care if the source file exists. In the [Files] section you can then use the onlyifdoesntexist flag for your last requirement. You can follow the commented version of this script if you want:

[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program

[Files]
Source: "My program"; DestDir: "{app}"; Flags: onlyifdoesntexist

[Code]
function GetFileName(const AFileName: string): string;
begin
  Result := ExpandConstant('{app}\' + AFileName);
end;

procedure CurStepChanged(CurStep: TSetupStep);
begin
  if (CurStep = ssInstall) then
  begin
    if not FileExists(GetFileName('My program v2')) then
      RenameFile(GetFileName('My program old'), GetFileName('My program v2'));
    if not FileExists(GetFileName('My program old')) then
      RenameFile(GetFileName('My program'), GetFileName('My program old'));
  end;
end;


标签: inno-setup