C# 安装时自动启动 Windows 服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1036713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:39:52  来源:igfitidea点击:

Automatically start a Windows Service on install

c#windows-services

提问by mickyjtwin

I have a Windows Service which I install using the InstallUtil.exe. Even though I have set the Startup Method to Automatic, the service does not start when installed, I have to manually open the services and click start. Is there a way to start it either via the command line, or through the code of the Service?

我有一个使用 InstallUtil.exe 安装的 Windows 服务。即使我将启动方法设置为自动,安装时服务也没有启动,我必须手动打开服务并单击启动。有没有办法通过命令行或服务代码启动它?

采纳答案by codemonkey

In your Installer class, add a handler for the AfterInstall event. You can then call the ServiceController in the event handler to start the service.

在您的安装程序类中,为 AfterInstall 事件添加一个处理程序。然后,您可以在事件处理程序中调用 ServiceController 来启动服务。

using System.ServiceProcess;
public ServiceInstaller()
{
    //... Installer code here
    this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
}

void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceInstaller serviceInstaller = (ServiceInstaller)sender;

    using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
    {
             sc.Start();
    }
}

Now when you run InstallUtil on your installer, it will install and then start up the service automatically.

现在,当您在安装程序上运行 InstallUtil 时,它会自动安装并启动该服务。

回答by Michael Klement

Automatic startup means that the service is automatically started when Windows starts. As others have mentioned, to start it from the console you should use the ServiceController.

自动启动是指服务在 Windows 启动时自动启动。正如其他人提到的,要从控制台启动它,您应该使用 ServiceController。

回答by Hemant

How about following commands?

遵循命令怎么样?

net start "<service name>"
net stop "<service name>"

回答by AlexDrenea

You can use the following command line to start the service:

您可以使用以下命令行启动服务:

net start *servicename*

回答by arbiter

Use ServiceControllerto start your service from code.

使用ServiceController从代码启动您的服务。

Update:And more correct way to start service from the command line is to use "sc" (Service Controller) command instead of "net".

更新:从命令行启动服务的更正确方法是使用“sc”(服务控制器)命令而不是“net”。

回答by adrianbanks

You can use the GetServicesmethod of ServiceControllerclass to get an array of all the services. Then, find your service by checking the ServiceNameproperty of each service. When you've found your service, call the Startmethod to start it.

您可以使用ServiceController类的GetServices方法来获取所有服务的数组。然后,通过检查每个服务的属性来找到您的服务。找到服务后,调用该方法以启动它。ServiceNameStart

You should also check the Statusproperty to see what state it is already in before calling start (it may be running, paused, stopped, etc..).

您还应该Status在调用 start 之前检查该属性以查看它已经处于什么状态(它可能正在运行、暂停、停止等)。

回答by Richard

Programmatic options for controlling services:

控制服务的编程选项:

  • Native code can used, "Starting a Service". Maximum control with minimum dependencies but the most work.
  • WMI: Win32_Servicehas a StartServicemethod. This is good for cases where you need to be able to perform other processing (e.g. to select which service).
  • PowerShell: execute Start-Servicevia RunspaceInvokeor by creating your own Runspaceand using its CreatePipelinemethod to execute. This is good for cases where you need to be able to perform other processing (e.g. to select which service) with a much easier coding model than WMI, but depends on PSH being installed.
  • A .NET application can use ServiceController
  • 可以使用本机代码,“启动服务”。最大程度的控制,最少的依赖,但最多的工作。
  • WMI:Win32_Service有一个StartService方法。这适用于您需要能够执行其他处理(例如选择哪个服务)的情况。
  • PowerShell:Start-Service通过RunspaceInvoke或通过创建自己RunspaceCreatePipeline方法并使用其方法执行来执行。这适用于您需要能够使用比 WMI 更简单的编码模型执行其他处理(例如选择哪个服务)的情况,但取决于安装的 PSH。
  • .NET 应用程序可以使用 ServiceController

回答by Pedro Pereira

After refactoring a little bit, this is an example of a complete windows service installer with automatic start:

稍加重构后,这是一个完整的 Windows 服务安装程序,具有自动启动的示例:

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace Example.of.name.space
{
[RunInstaller(true)]
public partial class ServiceInstaller : Installer
{
    private readonly ServiceProcessInstaller processInstaller;
    private readonly System.ServiceProcess.ServiceInstaller serviceInstaller;

    public ServiceInstaller()
    {
        InitializeComponent();
        processInstaller = new ServiceProcessInstaller();
        serviceInstaller = new System.ServiceProcess.ServiceInstaller();

        // Service will run under system account
        processInstaller.Account = ServiceAccount.LocalSystem;

        // Service will have Start Type of Manual
        serviceInstaller.StartType = ServiceStartMode.Automatic;

        serviceInstaller.ServiceName = "Windows Automatic Start Service";

        Installers.Add(serviceInstaller);
        Installers.Add(processInstaller);
        serviceInstaller.AfterInstall += ServiceInstaller_AfterInstall;            
    }
    private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
    {
        ServiceController sc = new ServiceController("Windows Automatic Start Service");
        sc.Start();
    }
}
}

回答by Guillaume Massé

You corrupted your designer. ReAdd your Installer Component. It should have a serviceInstaller and a serviceProcessInstaller. The serviceInstaller with property Startup Method set to Automatic will startup when installed and after each reboot.

你破坏了你的设计师。重新添加您的安装程序组件。它应该有一个 serviceInstaller 和一个 serviceProcessInstaller。属性 Startup Method 设置为 Automatic 的 serviceInstaller 将在安装时和每次重新启动后启动。

回答by Matsu Q.

Despite following the accepted answer exactly, I was still unable to get the service to start-- I was instead given a failure message during installation stating that the service that was just installed could not be started, as it did not exist, despite using this.serviceInstaller.ServiceNamerather than a literal...

尽管严格遵守了公认的答案,我仍然无法得到start--我的服务,而不是为给定的安装过程中指出,刚安装的服务无法开工,因为它不存在,尽管使用失败的消息this.serviceInstaller.ServiceName,而比文字...

I eventually found an alternative solution that makes use of the command line:

我最终找到了一个使用命令行的替代解决方案:

private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e) {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = "/C sc start " + this.serviceInstaller.ServiceName;

        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();
    }