C# 安装后自动启动windows服务

C# 安装后自动启动windows服务,c#,.net,windows-services,C#,.net,Windows Services,我有一个用c#编写的windows服务应用程序,我正试图在安装后立即启动它。该服务安装良好,没有错误或异常,但当我打开任务管理器并在安装后检查我的服务时,状态为“已停止”。我可以右键单击并启动服务,它工作正常。我知道提交发生在所有安装程序之后。我已经介绍了几个关于堆栈溢出的示例,但它仍然不会启动 这里是我的代码的一小部分,有什么想法可以让它在安装后自动启动吗 public example_project() { var processInstaller = new S

我有一个用c#编写的windows服务应用程序,我正试图在安装后立即启动它。该服务安装良好,没有错误或异常,但当我打开任务管理器并在安装后检查我的服务时,状态为“已停止”。我可以右键单击并启动服务,它工作正常。我知道提交发生在所有安装程序之后。我已经介绍了几个关于堆栈溢出的示例,但它仍然不会启动

这里是我的代码的一小部分,有什么想法可以让它在安装后自动启动吗

  public example_project()
    {
        var processInstaller = new ServiceProcessInstaller();
        var serviceInstaller = new ServiceInstaller();

        //set the privileges
        processInstaller.Account = ServiceAccount.LocalSystem;
        processInstaller.Username = null;
        processInstaller.Password = null;

        //service properties
        serviceInstaller.DisplayName = "example project";
        serviceInstaller.StartType = ServiceStartMode.Automatic;
        serviceInstaller.ServiceName = "example project";


        this.Installers.Add(processInstaller);
        this.Installers.Add(serviceInstaller);



        //update appconfig
        Console.WriteLine("Please enter the directory path of the of the target folder . . .");
        string target = Console.ReadLine();
        Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
        config.AppSettings.Settings.Add("target_directory", target);
        config.Save(ConfigurationSaveMode.Minimal);

        this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
    }


     void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
    {
        using (ServiceController controller = new ServiceController("example project"))
        {
            controller.Start();
        }
     }

可能是@GaryWalker的重复我已经使用过并尝试过这些解决方案,同样的问题仍然存在基于您提供的信息,并说您尝试过之前发布的解决方案,问题一定是其他原因——您是否正确拼写了服务,等等。使用提交()而不是AfterInstall()来执行此操作这应该不是问题。您是否正确安装了事件处理程序(按照正确的顺序等)。您的帖子中没有任何我可以看到的提示您可能做错了什么。我喜欢参考答案中显示的“完整代码”版本。我从来都不需要自己做这件事,但我不认为有什么东西可以阻止调试安装程序。我添加了我的完整代码,只是为了跟进任何可能遇到这个问题的人。我的代码可以在安装后自动启动。我没有捕捉到的程序稍后发生异常,它意外关闭。谢谢你的帮助@GaryWalker