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 section) and application-wide name-value pairs (stored in the config file’s 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

"1.0" encoding="utf-8" ?>

  
    "MyApp_Dev" connectionString="Data Source=SQL071;Initial Catalog=Awesome_Dev;Integrated Security=True"/>
    "MyApp_QA" connectionString="Data Source=SQL071;Initial Catalog=Awesome_Dev;Integrated Security=True"/>
    "MyApp_Prod" connectionString="Data Source=SQL071;Initial Catalog=Awesome_Dev;Integrated Security=True"/>
  
  
    "CompanyName" value="The Awesome Company"/>
    "PhoneNumber" value="(513) 555-4444"/>
  

We can accomplish the same functionality as the above app.config by creating 2 files: connections.config and appSettings.config and adding the following code to each file, respectively

connections.config:


  "MyApp_Dev" connectionString="Data Source=SQL071;Initial Catalog=Awesome_Dev;Integrated Security=True"/>
  "MyApp_QA" connectionString="Data Source=SQL071;Initial Catalog=Awesome_Dev;Integrated Security=True"/>
  "MyApp_Prod" connectionString="Data Source=SQL071;Initial Catalog=Awesome_Dev;Integrated Security=True"/>

appSettings.config:


  "CompanyName" value="The Awesome Company"/>
  "PhoneNumber" value="(513) 555-4444"/>

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

"1.0" encoding="utf-8" ?>

  "connections.config" />
  "appSettings.config" />
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”.