Multiple App.Config Files in .NET Class library project
Loading a different application configuration file at run time can be done using mapped configuration file. You need to add reference to System.Configuration.dll
in your project.
Set the value of Copy to Output Directory
property of all the additional config files (e.g. App1.config, App2.config etc.) other than the default one (App.config) to Copy if newer
. This way they will be available in the project output directory (\bin\debug) after the project has been built. Default value of this property is Do not copy
.
Here is the code snippet on how to read configuration data from non-default config files:
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = "App1.config"; // app1.config should be present in root directory from where application exe is kicked off
// Get the mapped configuration file
var config = ConfigurationManager.OpenMappedExeConfiguration(
configFileMap, ConfigurationUserLevel.None);
//get the relevant section from the config object
AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");
//get key value pair
var keyValueConfigElement = section.Settings["appSettingsKey"];
var appSettingsValue = keyValueConfigElement.Value;
If you have multiple app configuration files then you can keep a setting in default App.config
file with the help of which you can make a decision at run time about which additional config file to load e.g. App1.config
Note: Be aware that the code like ConfigurationManager.AppSettings["DeployEnv"]
will still read the data from the default App.config
file. This behavior can't be changed. Loading of default App.config
file can't be prohibited. You have to use alternate means as shown above to read the data from non-default configuration files
The app will use the config file named YourExcecutable.exe.config which is by default the file App.config included in your (executable) project. Note, that .NET only loads one config file for the whole application. You cannot use multiple configuration files (i.e. one per library project) without coding.
Option: You can use postbuild events and different solution configurations to copy one or another App.Config file to the output folder
Option: You can use the ConfigurationManager Class to load an alternate config file by code.