Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the version information of an installed service?

I want to check programmatically that the latest version of my Windows Service is installed. I have:

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

I don't see anything on the ServiceController interface that will tell me the version number. How do I do it?

like image 597
Shaul Behr Avatar asked Dec 29 '10 15:12

Shaul Behr


1 Answers

I am afraid there is no way other than getting the executable path from the registry as ServiceController does not provide that information.

Here is a sample I had created before:

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);
    }

After getting the exe path, just use FileVersionInfo.GetVersionInfo(exePath) class to get the version.

like image 179
Aliostad Avatar answered Oct 13 '22 06:10

Aliostad