确定服务是否已安装

5

我在安装Windows服务时,编写了一种替代installutil和命令行的方法:

IDictionary state = new Hashtable();
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(MyServiceClass).Assembly, args))
{
    IDictionary state = new Hashtable();
    inst.UseNewContext = true;
    //# Service Account Information
    inst.Install(state);
    inst.Commit(state);
}

安装它。我通过检测它是否成功启动来确定是否需要这样做。我预计在请求启动和实际设置其RunningOk标志之间会有延迟,并且更喜欢通用的编程解决方案。此(如何以编程方式在C#中安装Windows服务?http://dl.dropbox.com/u/152585/ServiceInstaller.cs 解决方案已经存在将近3年时间,并且很长,而且从我所知道的.NET方面来看,导入DLL似乎破坏了它的安全意图 。
因此,如果存在.NET的更简洁方法,则希望了解该方法是什么?
2个回答

11
为了查找一个服务以及判断它是否正在运行,
    private static bool IsServiceInstalled(string serviceName)
    {
        ServiceController[] services = ServiceController.GetServices();
        foreach (ServiceController service in services)
            if (service.ServiceName == serviceName) return true;
        return false;
    }

    private static bool IsServiceInstalledAndRunning(string serviceName)
    {
        ServiceController[] services = ServiceController.GetServices();
        foreach (ServiceController service in services)
            if (service.ServiceName == serviceName) return service.Status != ServiceControllerStatus.Stopped;
        return false;
    }

请注意,它实际上检查的是进程是否已停止而不是是否正在运行,但如果您希望,可以更改它。

在简洁的.NET结构中执行此操作很好。我不记得从哪里得到这些信息,但现在看起来如此容易,值得一篇文章。


使用Linq简化代码:ServiceController.GetServices().Any(s => s.ServiceName == serviceName); :) - tsemer
最好将它们包装到using块中: using( ServiceController[] sc= ServiceController.GetServices( ) ) { .. } - Astrogator

3
我建议使用Windows Installer本地支持来进行操作。
您可以管理服务的安装、卸载以及启动或停止操作。
不幸的是,并非所有的设置作者工具都直接支持此功能,因此您需要找到一个支持的工具。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接