12

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

Example 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:\> set TestKey=Bar
C:\> ConsoleApp2.exe
Key: Foo
sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • No, Microsoft detests environment variables far too much to consider to make that work. As well they should. You'll have to write the code, use Environment.GetEnvironmentVariable() to find out if it is set. – Hans Passant Sep 19 '18 at 11:18
  • @HansPassant, can the ConfigurationManager.AppSettings dictionary values be set programmatically but without affecting the underlying XML file? If so, I could execute some code at startup which reads the relevant properties from env vars and sets them. – sashoalm Sep 26 '18 at 14:41

3 Answers3

12

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.

For example:

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

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

    return value;
}
Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
DavidG
  • 113,891
  • 12
  • 217
  • 223
5

In .net 4.7.1 you can use ConfigurationBuilders to accomplish this.

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

René
  • 1,211
  • 2
  • 10
  • 3
2

in netcore (aspnetcore) you can override settings in environments https://github.com/dotnet/AspNetCore.Docs/issues/11361#issuecomment-471680877

need use prefix ASPNETCORE_youvariable (ASPNETCORE - default value).