简体   繁体   English

使用环境变量覆盖 App.config 值

[英]Override App.config value with an environment variable

I have a C# console program that prints an App.config value.我有一个打印 App.config 值的 C# 控制台程序。 Can I override this value from an environment variable?我可以从环境变量覆盖这个值吗?

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

Example App.config:示例 App.config:

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

Example Code:示例代码:

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

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

The ConfigurationManager class doesn't do that for you, it will only read from your app config. ConfigurationManager类不会为您执行此操作,它只会从您的应用程序配置中读取。 To fix this, you can use a function to get the variable and use that instead of calling ConfigurationManager.AppSettings directly.要解决此问题,您可以使用函数来获取变量并使用它,而不是直接调用ConfigurationManager.AppSettings 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.无论如何,这是一个很好的做法,因为这意味着您可以轻松地将配置移动到 JSON 文件或数据库中,并且您不需要更新旧方法的每次使用。

For example:例如:

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

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

    return value;
}

in netcore (aspnetcore) you can override settings in environments https://github.com/dotnet/AspNetCore.Docs/issues/11361#issuecomment-471680877在 netcore (aspnetcore) 中,您可以覆盖环境中的设置https://github.com/dotnet/AspNetCore.Docs/issues/11361#issuecomment-471680877

need use prefix ASPNETCORE_youvariable (ASPNETCORE - default value).需要使用前缀 ASPNETCORE_youvariable(ASPNETCORE - 默认值)。

In .net 4.7.1 you can use ConfigurationBuilders to accomplish this.在 .net 4.7.1 中,您可以使用 ConfigurationBuilders 来完成此操作。

See https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationbuilder?view=netframework-4.8请参阅https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationbuilder?view=netframework-4.8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM