用环境变量覆盖App.config值 [英] Override App.config value with an environment variable

查看:52
本文介绍了用环境变量覆盖App.config值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#控制台程序,可以打印App.config值.我可以从环境变量中覆盖此值吗?

I have a C# console program that prints an App.config value. Can I override this value from an environment variable?

在我的实际用例中,该值指定要绑定的端口,并且我需要在我的Jenkins服务器中运行该程序的多个实例,因此,即使每个实例使用相同的配置文件,它们也应具有不同的值.

In my real use-case, the value specifies a port to bind, and I need to run multiple instances of the program in my Jenkins server, so each one should have a different value even though they use the same config file.

示例App.config:

Example App.config:

  <appSettings>
    <add key="TestKey" value="Foo"/>
  </appSettings>

示例代码:

  Console.WriteLine($"Key: {ConfigurationManager.AppSettings["TestKey"]}");

我尝试仅设置Key名称,但是显然不起作用:

I tried just setting the Key name but that obviously doesn't work:

c:\Workspace\ConsoleApp2\ConsoleApp2\bin\Debug>set TestKey=Bar
c:\Workspace\ConsoleApp2\ConsoleApp2\bin\Debug>ConsoleApp2.exe
Key: Foo

推荐答案

ConfigurationManager 类不会为您执行此操作,它只会从您的应用程序配置中读取.要解决此问题,您可以使用函数来获取变量并使用该变量,而不是直接调用 ConfigurationManager.AppSettings .无论如何,这都是一个好习惯,因为这意味着您可以轻松地将配置移动到JSON文件或数据库中,而无需更新旧方法的所有用法.

The ConfigurationManager class doesn't do that for you, it will only read from your app config. To fix this, you can use a function to get the variable and use that instead of calling ConfigurationManager.AppSettings directly. This is good practice to do anyway as it means you can easily move your config into a JSON file or a database and you won';t need to update every usage of the old method.

例如:

public string GetSetting(string key)
{
    var value = Environment.GetEnvironmentVariable(key);

    if(string.IsNullOrEmpty(value))
    {
        value = ConfigurationManager.AppSettings[key];
    }

    return value;
}

这篇关于用环境变量覆盖App.config值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆