Get the user download folder path using Inno Setup? - inno-setup

How I get the user download folder path using Inno Setup?
[Code]
function InitializeSetup(): Boolean;
begin
if (FileExists(ExpandConstant('{%username%}\Downloads\file.txt'))) then
begin
MsgBox('Installation validated', mbInformation, MB_OK);
Result := True;
end
else
begin
MsgBox('Abort installation', mbCriticalError, MB_OK);
Result := False;
end;
end;
This always came to end in else part.
There is constant for "user docs" and "user desktop" but not for "download". Can anyone please help me how I get user "download" folder path.

The syntax for resolving environment variable is {%NAME}, not {%NAME%}. Moreover the USERNAME environment variable is not a path, it's just a username. You want USERPROFILE instead:
ExpandConstant('{%USERPROFILE}\Downloads\file.txt')
And hard-coding a path to Downloads folder seem like a bad idea to me. Who guarantees you that the file is there? I personally never download anything to the Downloads folder.
Aren't you actually looking for a file that is downloaded to the same folder, where your installer was downloaded to? Use {src} constant:
ExpandConstant('{src}\file.txt')
See Create small setup installer just for wizard, rest of files apart

Related

Change download location for Inno Setup TDownloadWizardPage

I'm using Inno Setup's download system, but I would like to change the download folder from {tmp} to another one, can someone help me?
of:
DownloadPage.Add('{#LinkJava}', ExpandConstant('{tmp}\Java.exe'), '');
for:
DownloadPage.Add('{#LinkJava}', ExpandConstant('{src}{#PastaGeralDeApps}{#PastaDownPlugins}{#NomeExeJava}'), '');
I'm creating an automatic installer and I need to store the apps in a folder, to use offline.
You cannot change the folder, where the files are downloaded to using TDownloadWizardPage (note that the BaseName argument of TDownloadWizardPage.Add accepts a filename only, not a path).
But you can copy over the files to the final folder, once they are downloaded.
[Files]
Source: "{tmp}\downloaded-file.exe"; DestDir: "{app}"; flags: external
You of course need to download the files before the actual installation. So for example from NextButtonClick(wpReady), the way the official CodeDownloadFiles.iss example does.
If you need to move the files to the final location before the installation, use RenameFile or FileCopy functions. The copying is obviously slower, but more reliable, as you cannot move/rename between disks/filesystems. You might try moving, falling back to copying, if moving fails.
//function that performs the download - OK
function DownloadFiles(Url, Destination, FileName, Hash : String): Boolean;
begin
DownloadPage.Clear;
DownloadPage.Add(Url, FileName, Hash);
DownloadPage.Show;
try
try
DownloadPage.Download;
Result := True;
except
if DownloadPage.AbortedByUser then
Log('Aborted by user.')
else
SuppressibleMsgBox(AddPeriod(GetExceptionMessage), mbCriticalError, MB_OK, IDOK);
Result := False;
end;
finally
FileCopyLogged(ExpandConstant('{tmp}\'+FileName), ExpandConstant(Destination+'\'+FileName), False);
end;
Result := True;
end;

Inno Setup: Can the installer update itself?

My installer creates a folder with my app and the installer itself. The installer is later on used as an updater for the application.
All of this works well but I would like to update the installer itself and not just my application.
I download a zip from my server and expect everything inside the zip to override everything in the app folder (including the installer itself).
Every time I run the installer I get an error that a file is already in use.
Can the installer update itself?
You cannot replace running application.
You have these options:
Start the "updater" via batch file (referring to assumed shortcut to the updater in a Start menu or any other method of invocation), that makes a copy of the installer to a temporary location and runs the updater from there. When updating, update the original copy.
To avoid the batch file (and an unpleasant console window), you can use JScript. Or even make the installer (updater) do this itself (create a copy of itself, launch the copy, exit itself).
Use restartreplace flag in Files section entry to schedule installer/updater replace for the next Windows start.
Keeping the installer in the {app} directory is probably acceptable for small applications, for larger ones consider an updater, or even another location, (in the form of a feature request) {Backup} to refer to a path on some flash or removable drive.
Run the setup from the {app} directory and after the version check, download the installer to the {tmp} folder.
Exec the installer thus before quitting, keeping mind of possible mutex conditions in the code section of your script:
if Exec(ExpandConstant('{tmp}\{OutputBaseFilename}), '', '', SW_SHOW,
ewNoWait, ResultCode) then
// success/fail code follows
To copy the installer back to {app} the Install script will have this in Files:
[Files]
Source: "{srcexe}"; DestDir: "{app}"; Flags: external
Presumably the above line will not produce an error when the installer is actually run from {app}.
Then, to clean up, the next time the installer is run from the {src} (= {app}) directory, the downloaded one can be removed from the {tmp} directory with
DeleteFile({tmp}\{OutputBaseFilename})
I've run into this same problem recently. We have a main installer that manages a bunch of other setup packages for our applications, and I wanted to add some mechanism for this main installer to update itself.
I've managed to find a solution creating a second Inno Setup package that serves just as an updater for the main installer, and that updater goes embedded in the main installer.
So, we have a XML file in our website that gives the latest version available for the main installer:
[ InstallerLastVersion.xml ]
<?xml version="1.0" encoding="utf-8"?>
<installer name="Our Central Installer" file="OurInstaller.exe" version="1.0.0.1" date="10/15/2021" />
The main code for this auto-update functionality in the main installer is that:
[ OurInstaller.iss ]
[Files]
; This file won't be installed ('dontcopy' flag), it is just embedded
; into the installer to be extracted and executed in case it's necessary
; to update the Installer.
Source: ".\OurInstallerUpdater.exe"; Flags: dontcopy
[Code]
const
UrlRoot = 'http://ourwebsite.com/';
// Downloads a XML file from a website and loads it into XmlDoc parameter.
function LoadXml(XmlFile: String; var XmlDoc: Variant): Boolean;
begin
XmlDoc := CreateOleObject('MSXML2.DOMDocument');
XmlDoc.async := False;
Result := XmlDoc.Load(UrlRoot + XmlFile);
end;
// Checks if there's a newer version of the Installer
// and fires the updater if necessary.
function InstallerWillBeUpdated(): Boolean;
var
XmlDoc: Variant;
LastVersion, Filename, Param: String;
ResultCode: Integer;
begin
if not LoadXml('InstallerLastVersion.xml', XmlDoc) then
begin
Result := False;
Exit;
end;
// Gets the latest version number, retrieved from
// the XML file download from the website.
LastVersion := XmlDoc.documentElement.getAttribute('version');
// If this installer version is the same as the one available
// at the website, there's no need to update it.
if '{#SetupSetting("AppVersion")}' = LastVersion then
begin
Result := False;
Exit;
end;
if MsgBox('There is an update for this installer.' + #13#10 +
'Do you allow this installer to be updated right now?',
mbConfirmation, MB_YESNO) = IDNO then
begin
Result := False;
Exit;
end;
// Extracts the updater, that was embedded into this installer,
// to a temporary folder ({tmp}).
ExtractTemporaryFile('OurInstallerUpdater.exe');
// Gets the full path for the extracted updater in the temp folder.
Filename := ExpandConstant('{tmp}\OurInstallerUpdater.exe');
// The current folder where the installer is stored is going to be
// passed as a parameter to the updater, so it can save the new version
// of the installer in this same folder.
Param := ExpandConstant('/Path={src}');
// Executes the updater, with a command-line like this:
// OurInstallerUpdater.exe /Path=C:\InstallerPath
Result := Exec(Filename, Param, '', SW_SHOW, ewNoWait, ResultCode);
end;
function InitializeSetup(): Boolean;
begin
// Checks if the installer needs to be updated and fires the update.
// If the update is fired the installer must be ended, so it can be
// replaced with the new version. Returning this InitializeSetup()
// function with False already makes the installer to be closed.
if InstallerWillBeUpdated() then
begin
Result := False;
Exit;
end;
Result := True;
end;
Now to the updater code (I'm using the "new" DownloadTemporaryFile() function added in Inno Setup 6.1):
[ OurInstallerUpdater.iss ]
[Code]
const
UrlRoot = 'http://ourwebsite.com/';
Installer = 'OurInstaller.exe';
function InitializeSetup(): Boolean;
var
DestinationPath: String;
ResultCode: Integer;
begin
// Retrieves the parameter passed in the execution
// of this installer, for example:
// OurInstallerUpdater.exe /Path=C:\InstallerPath
// If no parameter was passed it uses 'C:\InstallerPath' as default.
// (where {sd} is the constant that represents the System Drive)
DestinationPath := ExpandConstant('{param:Path|{sd}\InstallerPath}') + '\' + Installer;
try
// Downloads the newer version of the installer to {tmp} folder.
DownloadTemporaryFile(UrlRoot + Installer, Installer, '', nil);
// Copies the downloaded file from the temp folder to the folder where
// the current installer is stored, the one that fired this updater.
FileCopy(ExpandConstant('{tmp}\') + Installer, DestinationPath, False);
// Runs the updated installer.
Exec(DestinationPath, '', '', SW_SHOW, ewNoWait, ResultCode);
except
MsgBox('The file ''' + Installer + ''' could not be downloaded.', mbInformation, MB_OK);
end;
// Returning False from this function implies that this
// updater can now be finished, since its goal has already
// been reached (to update the main installer).
Result := False;
end;
In this setting you have to build OurInstallerUpdater.exe before OurInstaller.exe, since the first one is embedded into the second one.
Some sources:
Inno Setup: Install file from Internet
Using {AppVersion} as a parameter for a function in Inno Setup
Exit from Inno Setup installation from [Code]
Is it possible to accept custom command line parameters with Inno Setup
How to get the installer path in Inno Setup?

Uninstall everything even "newly created file by Application" using inno setup

I create installer for My Application "Demo"(.Net app) using INNO Setup. Install and Uninstall works smooth when without launching our application.
Uninstall not clean everything if Application is launch. Because my application update existing files and creating some files during Launch.
So how can we clean everything after launch also?
My script code available # script code
Thanks in advance
You can achieve that in 2 ways.
1st simple, but User will not be informed about deleting new/changed/additional files:
[UninstallDelete]
Type: filesandordirs; Name: "{app}"
{app} expands as a full path to you Application.
By default (basing on your snippet) it would be equal to DefaultDirName={pf}\{#MyAppName}\{#MyAppName}.
2nd from your Code snippet with Question MsgBox:
[Code]
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
if CurUninstallStep = usUninstall then begin
if MsgBox('Do you want to delete all data files?', mbConfirmation,
MB_YESNO) = IDYES
then begin
DelTree(ExpandConstant('{app}'), False, True, True);
//first False makes that the main Directory will not be deleted by function
//but it will be by the end of Uninstallation
end;
end;
end;

Inno Setup Script - running exe before installing

I wanna run an application before installing and I'm using this code on Inno Setup Script(Pascal):
function InitializeSetup():boolean;
var
ResultCode: integer;
begin
// Launch Notepad and wait for it to terminate
if ExecAsOriginalUser('{src}\MyFolder\Injector.exe', '', '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then
begin
// handle success if necessary; ResultCode contains the exit code
end
else begin
// handle failure if necessary; ResultCode contains the error code
end;
// Proceed Setup
Result := True;
end;
When I'm using "{win}\notepad.exe", It works but when I use "{src}\MyFolder\Injector.exe", Setup doesn't open my program and continues install.
Note : Injector has app.manifest which has 'requireAdministrator'. However this application should be run as administrator.
So what's wrong?
You need to use the ExpandConstant function when using values such as {src} in code.
However, InitializeSetup is also too early to run installation tasks. You should move this code into CurStepChanged(ssInstall).
Also, if it requires admin permissions it must be run with Exec, not ExecAsOriginalUser.
This May work for you... I believe that this problem is because of spaces in the entire path..that should overcome with double quoting the path...
Exec('cmd.exe','/c "'+ExpandConstant('{src}\MyFolder\Injector.exe')+'"', '',SW_SHOW,ewWaitUntilTerminated, ResultCode);
cheers..

Inno setup search for existing file

How can I search for an existing exe file and then use that directory for my installer ?
If the exe file is not found I would like the user to browse for the path. In case the exe file is installed somewhere else.
Senario 1 (most common cases):
Default dir is c:\test\My program
This should be shown as the path on the "Select Destination Location" page
When the user press Next, there should be a check. To make sure that the default dir exist (c:\test\My program)
If it exist, the user should just continue to the Ready to Install page.
Senario 2 (very seldom cases):
Default dir is c:\test\My program
This should be shown as the path on the "Select Destination Location" page
When the user press Next, there should be a check. To make sure that the default dir exist (c:\test\My program)
If it does not exist, the user should be prompt for the path to "My program". The user should afterwards continue to the Ready to Install page.
I then just trust that the user selects the correct path
How can I do this in InnoSetup ?
I do a similar thing with my installer already. The first thing I do is need to read the registry value from the program, and if that registry value is absent then I select that program's default directory. For example:
DefaultDirName={reg:HKLM\Software\Activision\Battlezone II,STInstallDir|reg:HKLM\Software\Activision\Battlezone II,Install121Dir|{pf32}\Battlezone II}
Now, the user runs the installer, and it has to check if the program is in the right folder. It does so by checking that the program's executable file already exists. I use this piece of code to do so.
{ Below code warns end user if he tries to install into a folder that does not contain bzone.exe. Useful if user tries to install into addon or any non-BZ2 folder. }
function NextButtonClick(CurPageID: Integer): Boolean;
begin
Log('NextButtonClick(' + IntToStr(CurPageID) + ') called');
case CurPageID of
wpSelectDir:
if not FileExists(ExpandConstant('{app}\bzone.exe')) then begin
MsgBox('Setup has detected that that this is not the main program folder of a Battlezone II install, and the created shortcuts to launch {#MyAppName} will not work.' #13#13 'You should probably go back and browse for a valid Battlezone II folder (and not any subfolders like addon).', mbError, MB_OK);
end;
wpReady:
end;
Result := True;
end;
The above code simply checks that the target executable exists and warns the user if it does not, giving him the chance to go back and change directories but also to go ahead with the install anyways.
Also, as you appear to be installing a patch or addon to an existing program, I recommend you set
DirExistsWarning=no
AppendDefaultDirName=false
And optionally to prevent an unnecessary screen if you are not creating start menu entries
DisableProgramGroupPage=yes
I would make a file input page and let user choose the Picture.exe binary location manually, when it won't be found on expected location.
You can follow the commented version of this code:
[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program
OutputDir=userdocs:Inno Setup Examples Output
[Files]
Source: "CurrentBinary.exe"; DestDir: "{app}"
Source: "PictureExtension.dll"; DestDir: "{code:GetDirPath}"
[Code]
var
FilePage: TInputFileWizardPage;
function GetDirPath(const Value: string): string;
begin
Result := '';
if FileExists(FilePage.Values[0]) then
Result := ExtractFilePath(FilePage.Values[0]);
end;
procedure InitializeWizard;
var
FilePath: string;
begin
FilePage := CreateInputFilePage(wpSelectDir, 'Select Picture.exe location',
'Where is Picture.exe installed ?', 'Select where Picture.exe is located, ' +
'then click Next.');
FilePage.Add('Location of Picture.exe:', 'Picture project executable|Picture.exe',
'.exe');
FilePage.Edits[0].ReadOnly := True;
FilePage.Edits[0].Color := clBtnFace;
FilePath := ExpandConstant('{pf}\Picture\Picture.exe');
if FileExists(FilePath) then
FilePage.Values[0] := FilePath;
end;

Resources