Search code examples
c#app-configconfiguration-files

Switching between config files in C#


Here I have two config files, I need to switch between these config files in C#

Example:

  1. app.config
  2. address.config

I need to change from app.config to address.config in runtime for fetching data.

I tried the below code:

System.Configuration.Configuration config
    = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.AppSettings.File = runtimeconfigfile;
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

Solution

  • This should work:

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = strConfigPath };
    Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
    

    When you want to switch files, you can change the ExeConfigFileName, and open mapped configuration again.