johnnie johnnie - 4 years ago 116
C# Question

How to have different parts of config file in c#

what I am trying to do is for my App.config file i have a bunch of settings, and what i want to do split up my config file into different files. For example; my app.config file file has setting pertaining to emails, so i want to take those settings out and store it in an email.config file and then in my app.config file use the configSource attribute to add thos settings from the email.config file and add it to the app settings node. Is this possible?

If so please advice on how to acheive the above result.

Many thanks.

so for example i have another config file called app1.config and has the following xml:

<?xml version="1.0" encoding="utf-8" ?>
<appSettings >
<add key="l" value="test"/>

and then from my main app.config file have a reference to the app1.config file and then from code be able to do this to get the value of the app setting key:

var x = ConfigurationManager.AppSettings["l"];

Answer Source

EDIT to reflect changed question and additional comments:

For custom settings defined in the <appSettings> part of the config file there is a file attribute that can contain the path to a file that overrides the appSettings parameters:

<?xml version="1.0" encoding="utf-8" ?>
 <appSettings file="settings.config">

You can indeed also use the configSource attribute, as specified in the MSDN documentation:

The ConfigSource property represents the value of the configSource attribute that is specified for a ConfigurationSection object that is associated with the SectionInformation object.

A ConfigurationSection implementation can optionally specify a separate file in which the configuration settings for that section are defined. This can be useful in multiple ways:

Using include files can result in a more logical and modular structure for configuration files.

File-access security and permissions can be used to restrict access to sections of configuration settings.

Settings in an include file that are not used during application initialization can be modified and reloaded without requiring an application restart.

The following example shows how this attribute is used in a configuration file to specify that the pages section is defined in an external include file:

<pages configSource="pages.config"/>

Or, if you want to store info from the same section in separate files, you can always revert to using the ConfigurationManager.Open...Configuration functions and read the settings programatically:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download