Change default app.config at runtime

后端 未结 8 1978
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 05:50

I have the following problem:
We have an application that loads modules (add ons). These modules might need entries in the app.config (e.g. WCF configuration). Because t

相关标签:
8条回答
  • 2020-11-22 06:47

    If your config file is just written with key/values in "appSettings", then you can read another file with such code :

    System.Configuration.ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
    configFileMap.ExeConfigFilename = configFilePath;
    
    System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
    AppSettingsSection section = (AppSettingsSection)configuration.GetSection("appSettings");
    

    Then you can read section.Settings as collection of KeyValueConfigurationElement.

    0 讨论(0)
  • 2020-11-22 06:55

    @Daniel solution works OK. A similar solution with more explanation is in c-sharp corner. For completeness I'd like to share my version: with using, and the bit flags abbreviated.

    using System;//AppDomain
    using System.Linq;//Where
    using System.Configuration;//app.config
    using System.Reflection;//BindingFlags
    
        /// <summary>
        /// Use your own App.Config file instead of the default.
        /// </summary>
        /// <param name="NewAppConfigFullPathName"></param>
        public static void ChangeAppConfig(string NewAppConfigFullPathName)
        {
            AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", NewAppConfigFullPathName);
            ResetConfigMechanism();
            return;
        }
    
        /// <summary>
        /// Remove cached values from ClientConfigPaths.
        /// Call this after changing path to App.Config.
        /// </summary>
        private static void ResetConfigMechanism()
        {
            BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Static;
            typeof(ConfigurationManager)
                .GetField("s_initState", Flags)
                .SetValue(null, 0);
    
            typeof(ConfigurationManager)
                .GetField("s_configSystem", Flags)
                .SetValue(null, null);
    
            typeof(ConfigurationManager)
                .Assembly.GetTypes()
                .Where(x => x.FullName == "System.Configuration.ClientConfigPaths")
                .First()
                .GetField("s_current", Flags)
                .SetValue(null, null);
            return;
        }
    
    0 讨论(0)
提交回复
热议问题