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

标签 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 文件获取服务名称和服务显示名称。

最佳答案

问题用这段代码解决了

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

关于c# - 如何从 app.config 获取 Windows 服务名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8516701/

相关文章:

c# - TransactionScope 导致阻塞?

qt - 如何使用 Qt 安装 Windows 服务?

windows-services - .Net Quartz Scheduler 2.3 无法在远程服务器上运行

c# - ExecuteNonQuery:连接属性尚未初始化

C# EPPLUS excel 数组公式解决方法

c# - 我可以在 Visual Studio 中自动缩进对齐代码吗?

c# - 事件查看器 — 记录到子文件夹?

创建自定义安装程序

c# - .net Windows 服务本地应用程序数据与普通应用程序中的数据不同

c# - 在代码的生命周期内处理异常的最佳方法是什么?