Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different app.config appSettings based on app.config value

I have app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>       
        <!--One set of properties-->
        <add key="Condition" value="A"/>
        <add key="DependingPropertyA" value="B"/>
        <add key="DependingPropertyB" value="C"/>
        <!--Another set of properties-->
        <add key="Condition" value="B"/>
        <add key="DependingPropertyA" value="D"/>
        <add key="DependingPropertyB" value="E"/>
    </appSettings>
</configuration>

So I want if Condition == A define one set of properties and if Condition == B - different set of properties so when I switch between A and B I don't need to change all other properties. Is it possible?

like image 384
Artur Shamsutdinov Avatar asked Sep 11 '25 22:09

Artur Shamsutdinov


1 Answers

If the property names are the same for each "Condition" (environment perhaps?), then you can do this with a little coding wizardry:

(App.Config:)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>       

    <!--Condition 'selector', change value to 'CondB' when you want to switch-->
    <add key="Condition" value="CondA"/>

    <add key="CondA.DependingPropertyA" value="B"/>
    <add key="CondA.DependingPropertyB" value="C"/>
    <add key="CondB.DependingPropertyA" value="D"/>
    <add key="CondB.DependingPropertyB" value="E"/>
  </appSettings>
</configuration>

Then, let's say, in your C# .NET code:

string keyPrepend = System.Configuration.ConfigurationManager.AppSettings["Condition"];

string propAValue = System.Configuration.ConfigurationManager.AppSettings[String.Format("{0}.{1}", keyPrepend, "DependingPropertyA")];
string propBValue = System.Configuration.ConfigurationManager.AppSettings[String.Format("{0}.{1}", keyPrepend, "DependingPropertyB")];

This let's you switch which set of key/values you want to use based on a single Condition key's value.

like image 85
ryancdotnet Avatar answered Sep 14 '25 13:09

ryancdotnet