Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variables in app.config for consuming inside app.config

Tags:

c#

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?

like image 319
schh Avatar asked Oct 17 '22 20:10

schh


1 Answers

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.

like image 150
kemiller2002 Avatar answered Oct 21 '22 00:10

kemiller2002