This is a mirror of official site: http://jasper-net.blogspot.com/

Moving Config Sections to External Files

| Monday, May 28, 2012
An App.config file or a Web.config file are great places to store configurable information – information that generally doesn’t change; but we want to be able to change easily (i.e., without rebuilding and redeploying the application.) Examples include connection strings (stored in the config file’s <connectionStrings> section) and application-wide name-value pairs (stored in the config file’s <appSettings> section).

We can add more flexibility by moving a section to an external file and linking to that file from the config file.

By splitting the file, we can manage and deploy only those settings separate from the rest of the configuration.

To do so, we create a new text file and copy that section into that file; then use the configSource attribute of the section tag in the original config file to point to the new file.

For example, the following app.config contains all the application’s connection strings and application settings

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="MyApp_Dev" connectionString="Data Source=SQL071;Initial Catalog=Awesome_Dev;Integrated Security=True"/>
    <add name="MyApp_QA" connectionString="Data Source=SQL071;Initial Catalog=Awesome_Dev;Integrated Security=True"/>
    <add name="MyApp_Prod" connectionString="Data Source=SQL071;Initial Catalog=Awesome_Dev;Integrated Security=True"/>
  </connectionStrings>
  <appSettings>
    <add key="CompanyName" value="The Awesome Company"/>
    <add key="PhoneNumber" value="(513) 555-4444"/>
  </appSettings>
</configuration>

...
...

Then, point to these files in the app.config, as shown below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings configSource="connections.config" />
  <appSettings configSource="appSettings.config" />
</configuration>

One caveat to doing this: The configSource files (connections.config and appSettings.config in our example) must be in the same folder as the config file. We can accomplish this by selecting each configSource file in Solution Explorer and setting its Copy to Output directory property to either “Copy always” or “Copy if newer”.

QR: Inline image 1

Posted via email from Jasper-net

0 comments: