Using InstallUtil to install a Windows service with startup parameters

后端 未结 2 879
走了就别回头了
走了就别回头了 2020-12-14 10:58

I am using InstallUtil to install my service and I just cannot figure out how to specify the startup parameters for it!

Here is my Installer subclass:



        
相关标签:
2条回答
  • 2020-12-14 11:09

    I know this is an old post but thought I'd post my response. I did this in a .net 4 service using the BeforeInstall event.

    The ServiceProcessInstaller's BeforeInstall event:

    private void serviceProcessInstaller1_BeforeInstall(object sender, InstallEventArgs e)
    {
        System.ServiceProcess.ServiceProcessInstaller installer = sender as System.ServiceProcess.ServiceProcessInstaller;
    
        if (installer != null)
        {
            //Get the existing assembly path parameter
            StringBuilder sbPathWIthParams = new StringBuilder(installer.Context.Parameters["assemblypath"]);
    
            //Wrap the existing path in quotes if it isn't already
            if (!sbPathWIthParams[0].Equals("\""))
            {
                sbPathWIthParams.Insert(0, "\"");
                sbPathWIthParams.Append("\"");
            }
    
            //Add desired parameters
            sbPathWIthParams.Append(" test");
    
            //Set the new path
            installer.Context.Parameters["assemblypath"] = sbPathWIthParams.ToString();
        }
    }
    

    The installed service looks as follows:

    It executes fine, and I can examine the parameters from within the main function of the service.

    0 讨论(0)
  • 2020-12-14 11:12

    Found it.

    I have rewritten the Install method like so:

    public override void Install(IDictionary stateSaver)
    {
      string userName = this.Context.Parameters["username"];
      if (userName == null)
      {
        Console.WriteLine(s_usage);
        throw new InstallException("Missing parameter 'username'");
      }
    
      string userPass = this.Context.Parameters["password"];
      if (userPass == null)
      {
        Console.WriteLine(s_usage);
        throw new InstallException("Missing parameter 'password'");
      }
    
      m_serviceProcessInstaller.Username = userName;
      m_serviceProcessInstaller.Password = userPass;
    
      var path = new StringBuilder(Context.Parameters["assemblypath"]);
      if (path[0] != '"')
      {
        path.Insert(0, '"');
        path.Append('"');
      }
      path.Append(" --service");
      Context.Parameters["assemblypath"] = path.ToString();
      base.Install(stateSaver);
    }
    

    Although, I give the predefined command line parameters (--service), the code is easily adaptable to pass real command line arguments, just use the same pattern for passing the username and password parameters.

    0 讨论(0)
提交回复
热议问题