Credentials when Installing Windows Service

前端 未结 4 1257
野性不改
野性不改 2021-02-01 00:34

I am attempting to install a C# windows service project using a VisualStudio.Net deployment project.

To run the deployment project I right-click and select \"install\"

4条回答
  •  滥情空心
    2021-02-01 01:26

    In the project that contains the service, add an Installer class. Make it look something like this:

    [RunInstaller(true)]
    public class MyServiceInstaller : Installer
    {
        public MyServiceInstaller()
        {
            ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
            serviceProcessInstaller.Account = ServiceAccount.LocalSystem; // Or whatever account you want
    
            var serviceInstaller = new ServiceInstaller
            {
                DisplayName = "Insert the display name here",
                StartType = ServiceStartMode.Automatic, // Or whatever startup type you want
                Description = "Insert a description for your service here",
                ServiceName = "Insert the service name here"
            };
    
            Installers.Add(_serviceProcessInstaller);
            Installers.Add(serviceInstaller);
        }
    
        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);
    
            // This will automatically start your service upon completion of the installation.
            try
            {
                var serviceController = new ServiceController("Insert the service name here");
                serviceController.Start();
            }
            catch
            {
                MessageBox.Show(
                    "Insert a message stating that the service couldn't be started, and that the user will have to do it manually");
            }
        }
    }
    

    Then, in the solution explorer, right-click on the deployment project and select "View > Custom Actions". Right-click on Custom Actions, and select "Add Custom Action..." Pick the Application Folder and select the primary output of the project that contains the service. Now the custom actions (Commit from above) will be executed upon installation. You can add the additional methods (Install, Rollback, Uninstall) if you need other custom actions.

提交回复
热议问题