获取已安装服务的版本信息?

Sha*_*ica 6 c# windows-services

我想以编程方式检查是否安装了最新版本的Windows服务.我有:

var ctl = ServiceController.GetServices().Where(s => s.ServiceName == "MyService").FirstOrDefault();
if (ctl != null) {
  // now what?
}
Run Code Online (Sandbox Code Playgroud)

我在ServiceController界面上看不到任何告诉我版本号的东西.我该怎么做?

Ali*_*tad 9

我担心除了从注册表获取可执行文件路径之外别无他法,因为ServiceController没有提供该信息.

这是我之前创建的示例:

private static string GetExecutablePathForService(string serviceName, RegistryView registryView, bool throwErrorIfNonExisting)
    {
        string registryPath = @"SYSTEM\CurrentControlSet\Services\" + 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);
    }
Run Code Online (Sandbox Code Playgroud)

获取exe路径后,只需使用FileVersionInfo.GetVersionInfo(exePath)类来获取版本.

  • 那应该给你 FileVersion,而你提到的是 AssemblyVersion。如果您需要 AssemblyVersion,那么您必须将其作为程序集加载(如您所述)。但是 **注意** 一旦你加载了它,你就锁定了文件(即使你作为 ReflectionOnly 加载)直到你的进程终止。 (2认同)