获取已安装服务的版本信息?
我想以编程方式检查是否安装了最新版本的Windows服务。 我有:
var ctl = ServiceController.GetServices().Where(s => s.ServiceName == "MyService").FirstOrDefault(); if (ctl != null) { // now what? }
我在ServiceController
接口上看不到任何会告诉我版本号的内容。 我该怎么做?
我担心除了从注册表获取可执行文件路径之外别无其他方法,因为ServiceController
不提供该信息。
这是我之前创建的示例:
private static string GetExecutablePathForService(string serviceName, RegistryView registryView, bool throwErrorIfNonExisting) { string registryPath = @"SYSTEMCurrentControlSetServices" + serviceName; RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView).OpenSubKey(registryPath); if(key==null) { if (throwErrorIfNonExisting) throw new ArgumentException("Non-existent service: " + serviceName, "serviceName"); else return null; } string value = key.GetValue("ImagePath").ToString(); key.Close(); if(value.StartsWith(""")) { value = Regex.Match(value, ""([^"]+)"").Groups[1].Value; } return Environment.ExpandEnvironmentVariables(value); }
获取exe路径后,只需使用FileVersionInfo.GetVersionInfo(exePath)
类来获取版本。
如果您拥有该服务,则可以将版本信息放入DisplayName
,例如DisplayName="MyService 2017.06.28.1517"
。 这允许您查找服务的现有安装并解析版本信息:
var ctl = ServiceController .GetServices() .FirstOrDefault(s => s.ServiceName == "MyService"); if (ctl != null) { // get version substring, you might have your own style. string substr = s.DisplayName.SubString("MyService".Length); Version installedVersion = new Version(substr); // do stuff, eg check if installed version is newer than current assembly. }
如果要避免注册表,这可能很有用。 问题是,服务条目可以根据安装例程转到注册表的不同部分。
上述就是C#学习教程:获取已安装服务的版本信息?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/989308.html