使用InstallUtil安装具有启动参数的Windows服务

mar*_*ark 14 .net c# windows-services installutil

我使用InstallUtil来安装我的服务,我只是无法弄清楚如何为它指定启动参数!

这是我的Installer子类:

[RunInstaller(true)]
public class ServerHostInstaller : Installer
{
  private ServiceInstaller m_serviceInstaller;
  private ServiceProcessInstaller m_serviceProcessInstaller;
  private static string s_usage = "Usage:\ninstallutil /i /username=<user_name> /password=<user_password> NCStub.Server.Host.exe";

  public ServerHostInstaller()
  {
    m_serviceInstaller = new ServiceInstaller();
    m_serviceInstaller.ServiceName = Program.ServiceName;
    m_serviceInstaller.DisplayName = Program.ServiceName;
    m_serviceInstaller.StartType = ServiceStartMode.Automatic;

    m_serviceProcessInstaller = new ServiceProcessInstaller();
    m_serviceProcessInstaller.Account = ServiceAccount.User;

    Installers.Add(m_serviceInstaller);
    Installers.Add(m_serviceProcessInstaller);
  }

  public override void Install(IDictionary stateSaver)
  {
    base.Install(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;
  }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以指出我如何指定服务启动参数?

mar*_*ark 15

找到了.

我已经重写了Install方法,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)

虽然,我给预定义的命令行参数(--service)时,代码是容易适应实际传递命令行参数,只要使用相同的模式用于传递的用户名口令参数.

  • 如果将处理程序附加到服务安装程序对象的BeforeInstall事件而不是重写Install方法,则此方法也适用. (2认同)
  • 实际上没有它没有.它应该和我相当确定它曾经,但我只是检查,它没有.坚持覆盖版本. (2认同)
  • 此解决方案不起作用.它产生以下命令,如服务:""C:\ folder\file.exe" - service" (2认同)