作为安装我的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做一个更简洁的方法,如果有的话?
答案 0 :(得分: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构造中执行此操作。不要记得我从哪里获得信息,但现在看起来很容易,值得发帖。
答案 1 :(得分:3)
我建议使用Windows Installer native support。
您可以管理服务的安装,卸载以及启动或停止操作。
不幸的是,并非所有设置编写工具都为此提供直接支持,因此您需要找到一个支持工具。