作为安装 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/