Change default app.config at runtime

后端 未结 8 2094
伪装坚强ぢ
伪装坚强ぢ 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: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
    
        /// 
        /// Use your own App.Config file instead of the default.
        /// 
        /// 
        public static void ChangeAppConfig(string NewAppConfigFullPathName)
        {
            AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", NewAppConfigFullPathName);
            ResetConfigMechanism();
            return;
        }
    
        /// 
        /// Remove cached values from ClientConfigPaths.
        /// Call this after changing path to App.Config.
        /// 
        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;
        }
    

提交回复
热议问题