Change default app.config at runtime

后端 未结 8 2125
伪装坚强ぢ
伪装坚强ぢ 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:31

    You can try to use Configuration and Add ConfigurationSection on runtime

    Configuration applicationConfiguration = ConfigurationManager.OpenMappedExeConfiguration(
                            new ExeConfigurationFileMap(){ExeConfigFilename = path_to_your_config,
                            ConfigurationUserLevel.None
                            );
    
    applicationConfiguration.Sections.Add("section",new YourSection())
    applicationConfiguration.Save(ConfigurationSaveMode.Full,true);
    

    EDIT: Here is solution based on reflection (not very nice though)

    Create class derived from IInternalConfigSystem

    public class ConfigeSystem: IInternalConfigSystem
    {
        public NameValueCollection Settings = new NameValueCollection();
        #region Implementation of IInternalConfigSystem
    
        public object GetSection(string configKey)
        {
            return Settings;
        }
    
        public void RefreshConfig(string sectionName)
        {
            //throw new NotImplementedException();
        }
    
        public bool SupportsUserConfig { get; private set; }
    
        #endregion
    }
    

    then via reflection set it to private field in ConfigurationManager

            ConfigeSystem configSystem = new ConfigeSystem();
            configSystem.Settings.Add("s1","S");
    
            Type type = typeof(ConfigurationManager);
            FieldInfo info = type.GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static);
            info.SetValue(null, configSystem);
    
            bool res = ConfigurationManager.AppSettings["s1"] == "S"; // return true
    

提交回复
热议问题