【问题标题】:How to get windows service name from app.config如何从 app.config 获取 Windows 服务名称
【发布时间】:2011-12-15 07:46:18
【问题描述】:

我有一个 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 完成它的工作),否则您实际上不会更改服务名称。对于必须维护的人来说,这可能会让人感到困惑。
  • @Pete 我想用两个不同的名称运行服务。
  • @sinanakyazici 它对我有用!非常感谢

标签: c# windows-services


【解决方案1】:

这个代码解决了问题

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我在安装 Windows 服务时使用 ConfigurationManager,出现错误。 System.Reflection.TargetInvocationException:调用的目标已引发异常。引发内部异常 System.ArgumentException 并显示以下错误消息:服务名称包含无效字符、为空或太长(最大长度 = 80)..
    • 检查一下它会帮助你 - stackoverflow.com/questions/5030416/…
    猜你喜欢
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 2013-03-12
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多