mic*_*win 117 c# windows-services
我有一个Windows服务,我使用InstallUtil.exe安装.即使我已将启动方法设置为自动,但安装时服务无法启动,我必须手动打开服务并单击开始.有没有办法通过命令行或通过服务代码启动它?
cod*_*key 215
在Installer类中,为AfterInstall事件添加处理程序.然后,您可以在事件处理程序中调用ServiceController来启动该服务.
using System.ServiceProcess;
public ServiceInstaller()
{
    //... Installer code here
    this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
}
void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
现在,当您在安装程序上运行InstallUtil时,它将安装然后启动该服务.
Ped*_*ira 27
重构一下后,这是一个完整的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();
    }
}
}
以下命令怎么样?
net start "<service name>"
net stop "<service name>"
控制服务的编程选项:
StartService方法。这适用于您需要能够执行其他处理(例如选择哪个服务)的情况。Start-Service通过RunspaceInvoke或通过创建自己Runspace的CreatePipeline方法并使用其方法执行来执行。这适用于您需要能够使用比 WMI 更简单的编码模型执行其他处理(例如选择哪个服务)的情况,但取决于安装的 PSH。ServiceController| 归档时间: | 
 | 
| 查看次数: | 95776 次 | 
| 最近记录: |