Override App.config value with an environment variable
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;
}
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