c# - 判断服务是否已经安装

标签 c# .net windows-services windows-installer

作为安装 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 标志之间会有延迟,而宁愿是一个通用的、程序化的解决方案。 ( How to install a windows service programmatically in C#? ) http://dl.dropbox.com/u/152585/ServiceInstaller.cs解决方案已有将近 3 年的历史,很长,并且从我对 .NET 的了解来看,导入 DLL 似乎违背了它的安全意图。

因此,我想知道一种更简洁的方法来使用 .NET 执行此操作(如果存在的话)?

最佳答案

要查找服务,以及它是否正在运行,

    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 结构中做到这一点。不记得我从哪里得到的信息,但现在看起来很简单,值得一贴。

关于c# - 判断服务是否已经安装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7381508/

相关文章:

c# - C#404错误(Webclient)

javascript - 调试从 JavaScript 调用的 .cs 文件

c# - 翻转窗口c#.net

java - 如何通过 NSIS 脚本使 prunsvr 工作

c# - 为什么 RequestAdditionalTime() 方法在 Vista/7 中重启时不起作用?

c# - 如何在关闭前检查所有作业是否运行完毕? - quartz 网

c# - 你可以传递没有类型参数的泛型委托(delegate)吗?

c# - 如何选择 serviceStatus.dwWaitHint 的值?

.net - 如何在 VB.NET 中声明嵌套函数?

.net - 如何在新行上使用关闭节点和标签来格式化 XML?