How can a Windows Service determine its ServiceName?

后端 未结 7 896
春和景丽
春和景丽 2020-11-27 05:53

I\'ve looked and couldn\'t find what should be a simple question:

How can a Windows Service determine the ServiceName for which it was started?

7条回答
  •  一向
    一向 (楼主)
    2020-11-27 06:46

    I had a chicken-and-egg problem where I needed to know the service location before completing Service.Run() (Service could be part of a client or server installation, installer named them appropriately, and I needed to detect which it was on startup)

    I relied on the registry to get me the name.

    public String IdentifySelfFromRegistry()
    {
        String executionPath = Assembly.GetEntryAssembly().Location;
        Microsoft.Win32.RegistryKey services = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
                @"SYSTEM\CurrentControlSet\services");
        if (services != null)
        {
            foreach(String subkey in services.GetSubKeyNames())
            {
                if (executionPath.Equals(ServicePathFromServiceKey(services.OpenSubKey(subkey))))
                    return subkey;
            }
        }
        return String.Empty;
    }
    
    protected static String ServicePathFromServiceKey(Microsoft.Win32.RegistryKey serviceKey)
    {
        if (serviceKey != null)
        {
            String exec = serviceKey.GetValue(ServicePathEntry) as String;
            if (exec != null)
                return exec.Trim('\"');
        }
        return String.Empty;
    }
    

提交回复
热议问题