2

I know that I can define variable (key-value) in AppConfig and use it in my C# code. However, the question is: is it possible to define variable in AppConfig and use it in AppConfig (something like global constant) ?

For example,

address = "8.8.8.8"
...
url = "jdbc..$address..."
...

1 Answers1

1

No, you can't do it directly as you'd like.

What you can do, however, is to parse the value in the code by yourself and look for the other variables in the config file. Like this:

public string GetFromConfigWithVars(string key)
{
    string value = ConfigurationManager.AppSettings[key];

    foreach (string var in value.Split('{', '}'))
    {
        string val = ConfigurationManager.AppSettings[var];
        value = value.Replace($"{{{var}}}", val);
    }

    return value;
}

Then, you can have a configuration like this:

<appSettings>
   <add key="var1" value="First"/>
   <add key="var2" value="Last"/>
   <add key="myKey" value="{var1}----{var2}"/>
</appSettings>

And call it in code: string myValue = this.GetFromConfigWithVars("myKey")

This will give back: First----Last

You can also look here for other ideas and suggestions

Community
  • 1
  • 1
Ofir Winegarten
  • 8,588
  • 2
  • 17
  • 25