如何从app.config获取Windows服务名称

时间:2011-12-15 07:46:19

标签: c# windows-services

我有一个app.config

  <appSettings>
    <add key="ServiceName" value="HasService"/>
    <add key="ServiceDisplayName" value="HasService"/>
  </appSettings>

我的服务安装程序类

 [RunInstaller(true)]
    public class MyServiceInstaller : System.Configuration.Install.Installer
    {
        public MyServiceInstaller()
        {
            var process = new ServiceProcessInstaller {Account = ServiceAccount.LocalSystem};
            var serviceAdmin = new ServiceInstaller
            {
                StartType = ServiceStartMode.Manual,
                ServiceName = "HasService",
                DisplayName = "HasService"
            };
            Installers.Add(process);
            Installers.Add(serviceAdmin);
        }
    }

我想从app.config获取服务名称。

    var serviceAdmin = new ServiceInstaller
    {
        StartType = ServiceStartMode.Manual,
        ServiceName = GetServiceNameAppConfig("ServiceName"),
        DisplayName = GetServiceNameAppConfig("ServiceDisplayName")
    };

    public string GetServiceNameAppConfig(string serviceName)
    {
        //what should i write here?
    }

如何从MyServiceInstaller类中的app.config文件获取服务名称和服务显示名称。

2 个答案:

答案 0 :(得分:20)

问题通过此代码解决

public string GetServiceNameAppConfig(string serviceName)
{
    var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetAssembly(typeof(MyServiceInstaller)).Location);
    return config.AppSettings.Settings[serviceName].Value;
}

答案 1 :(得分:0)

你试过这个吗 - configurationmanager.appsettings["yourkey"]