5

I have an app.config file where i have the same value many many times in the file and would like to be able to change it in one place.

Something like:

<appSettings>
    <add key="dbHostAddress" value="localhost" />
</appSettings>

and then consume it for my Data Souce value in my connectionstring like below for example

<connectionStrings><add name="ConnectionString" connectionString="Data Source=I WOULD LIKE TO ACCESS THE VALUE HERE;Initial Catalog=Database;Integrated Security=True;Connect Timeout=15" /></connectionStrings>    

Can i do this somehow?

schh
  • 232
  • 1
  • 11
  • Possible duplicate of [Variables within app.config/web.config](http://stackoverflow.com/questions/603009/variables-within-app-config-web-config) – Todd Sprang Dec 21 '16 at 14:27

1 Answers1

3

You can always do something like this in code:

var host = System.Configuration.ConfigurationManager.AppSettings["dbHostAddress"]

var connectionString = System.Configuration.ConfigurationManager.
   ConnectionStrings["ConnectionString"]
  .ConnectionString.Replace("REPLACE_VALUE",host);

You just store the connection string with a placeholder and then pull it into code and swap out the placeholder value with what you want.

Data Source=REPLACE_VALUE;Initial Catalog=Database;
    Integrated Security=True;Connect Timeout=15

I would then create a wrapper class around the configuration values so this happens automatically when you access the property in code.

kemiller2002
  • 107,653
  • 27
  • 187
  • 244
  • Im sure the above would work. I was hoping it was possible to do this without code. I guess my question was if i can declare and consume variables in xml. the connectionstring usecase was just an example. i have other usecases where it would probably be alot more complicated. Thanks – schh Dec 22 '16 at 09:39