Reputation: 391
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?
Upvotes: 5
Views: 2431
Reputation: 115548
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.
Upvotes: 3