2011-12-15 26 views
5

Windows服务名称我有一个的app.config如何从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文件中获取服务名称和服务显示名称。

+0

你为什么要这么做?我可以看到把“有可能改变某一天的东西”放到配置文件中的争论,但是你会认真地将服务的名称放在这个类别中吗?您也可以根据需要更改配置文件,但除非您重新安装该服务(即除非MsServiceInstaller完成其任务),否则实际上不会更改服务名称。这可能会让人不知所措。 – PeteH

+0

@Pete我想用两个不同的名字来运行服务。 – sinanakyazici

+0

@sinanakyazici它为我工作!非常感谢 –

回答

18

问题解决与此代码

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

这对我完美的作品。 – Daniel

0

你尝试过这一点 - configurationmanager.appsettings["yourkey"]

+0

我在安装Windows服务时使用ConfigurationManager发生错误。 System.Reflection.TargetInvocationException:异常已被引发的调用引发。 内部异常System.ArgumentException抛出的错误如下 消息:服务名称包含无效字符,为空或者太长(m ax length = 80)。 – sinanakyazici

+1

检查它会帮助你 - http: //stackoverflow.com/questions/5030416/setup-project-custom-installer-connection-string –