安装 Windows 服务时,如何以编程方式使其使用特定的域帐户

Bla*_*man 2 installation service windows-services

我有一个运行良好的 Windows 服务,但我必须让它在特殊用户帐户下运行。

目前,我进入服务并更改登录方式部分,但对于部署来说,这必须更专业地完成。

有没有办法让我以编程方式或在服务安装过程中以自定义用户帐户身份登录?

Cha*_*ana 5

当您打开服务控制管理器(SCM)时,当然会有一个标有“登录”的选项卡。您可以在其中指定它应在哪个域或计算机帐户下运行...

但以编程方式。如果您在代码中使用服务安装程序类,您可以在那里指定它。

 public class MyServiceInstaller : Installer
    {
        private ServiceInstaller servInst;
        private ServiceProcessInstaller servProcInst;
        public MyServiceInstaller () { InitializeComponent(); }

        #region Component Designer generated code
        private void InitializeComponent()
        {
            servInst = new ServiceInstaller();
            servProcInst = new ServiceProcessInstaller();
            // -----------------------------------------------
            servProcInst.Account = ServiceAccount.LocalSystem; // or whatever accnt you want
            servProcInst.Username = null;  // or, specify a specifc acct here
            servProcInst.Password = null;
            servProcInst.AfterInstall += 
                new InstallEventHandler(this.AfterServProcInstall);
            servInst.ServiceName = "MyService";
            servInst.DisplayName = "Display name for MyService";
            servInst.Description = " Description for my service";
            servInst.StartType = ServiceStartMode.Automatic;
            servInst.AfterInstall += 
               new InstallEventHandler(this.AfterServiceInstall);
            Installers.AddRange(new Installer[] { servProcInst, servInst });
        }
        #endregion
    }
    private void AfterServiceInstall(object sender, InstallEventArgs e) { }
    private void AfterServProcInstall(object sender, InstallEventArgs e) { }
Run Code Online (Sandbox Code Playgroud)