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

6
我有一个 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文件获取服务名称和服务显示名称。


你为什么要这样做呢?我可以理解将“可能会改变的东西”放入配置文件的论点,但您真的会将服务名称归类于此类别吗?另外,您可以随意更改配置文件,但除非重新安装服务(即除非MsServiceInstaller执行其操作),否则您实际上不会更改服务名称。对于需要维护的人来说,这可能会带来困惑。 - PeteH
2
@Pete 我想要用两个不同的名称运行这项服务。 - Sinan AKYAZICI
2个回答

23

这段代码解决了问题

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

0

你尝试过这样写吗 - configurationmanager.appsettings["yourkey"]


我在安装 Windows 服务时使用 ConfigurationManager,但出现了错误。System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. 内部异常 System.ArgumentException 抛出以下错误消息:Service name contains invalid characters, is empty, or is too long (max length = 80)。 - Sinan AKYAZICI
1
请查看此链接,它会帮助你解决问题 - http://stackoverflow.com/questions/5030416/setup-project-custom-installer-connection-string - Nitin Rastogi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接