【问题标题】:Determining whether a service is already installed确定服务是否已安装
【发布时间】:2011-11-14 22:34:59
【问题描述】:

作为安装 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 年的历史了,并且导入了 DLL,从我对 .NET 的了解来看,这似乎违背了它的安全意图。

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

【问题讨论】:

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


    【解决方案1】:

    我建议使用Windows Installer native support

    您可以管理服务安装、卸载以及启动或停止操作。

    很遗憾,并非所有设置创作工具都对此提供直接支持,因此您需要找到一个可以提供直接支持的工具。

    【讨论】:

      【解决方案2】:

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

          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); :)
      • 最好将它们包装到 using-blocks 中:using( ServiceController[] sc= ServiceController.GetServices( ) ) { .. }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 2018-08-28
      • 1970-01-01
      • 2013-02-12
      相关资源
      最近更新 更多