Search code examples
windowsdelphiservice

Get path of Windows service EXE (to use as a parameter at installation and runtime)


Is it possible to get the path of the Windows service EXE

  1. at installation time, to modify the service display name, and
  2. at runtime, to use as a parameter?

GetCurrentDir etc. of course gives system32 folder.

The problem I would like to solve is that I want multiple instances of it running, with a parameter passed to it which will determine name and behaviour. My proposed solution was to use a folder name, e.g.:

C:\MyProgramDirectory\bin\1\MyService.exe
C:\MyProgramDirectory\bin\2\MyService.exe
C:\MyProgramDirectory\bin\3\MyService.exe

I want the service to

  • pick up this directory name at install, so its service/display name would be "MyServiceX":
    procedure TMyService.ServiceLoadInfo(Sender: TObject);
      begin
    
        name        := 'MyServiceX'; // Get this by extracting X from EXE directory
        DisplayName := 'MyServiceX'; // Get this by extracting X from EXE directory
      end;
    
    procedure TMyService.ServiceBeforeInstall(Sender: TService);
      begin
        ServiceLoadInfo(Sender);
        inherited;
      end;
    
    procedure TMyService.ServiceBeforeUninstall(Sender: TService);
      begin
        ServiceLoadInfo(Sender);
        inherited;
      end;
    
  • pick up this directory name at runtime to use as a parameter to determine behaviour

Solution

  • The service can get its own .exe file path by calling ParamStr(0).

    However, a cleaner solution that doesn't require having multiple copies of the .exe is to pass extra command-line parameters when (un)installing and running the service. The service can look for those parameters to update its Name/DisplayName as needed. See this question for how to do that:

    Is it possible to install multiple instances of the same delphi service application?