Dynamically modify the default app.config
Problem description:
Develop a solution that can dynamically load the configuration section from dynamically loaded application modules to the new memory app.config to ensure that the application is transparent to the modified configuration without covering the default app. config.
Solution:
Related issues are recommended to use the method to change the configuration system path, but this is only valid when the configuration system is first used for the first time. In order to completely solve this problem, the cache configuration value also needs to be cleared.
Implement: SetData
How to use:
To temporarily modify the specific range of app.config:
<code class="language-csharp">using System; using System.Configuration; using System.Linq; using System.Reflection; public abstract class AppConfig : IDisposable { public static AppConfig Change(string path) { return new ChangeAppConfig(path); } public abstract void Dispose(); private class ChangeAppConfig : AppConfig { private readonly string oldConfig = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString(); private bool disposedValue; public ChangeAppConfig(string path) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path); ResetConfigMechanism(); } public override void Dispose() { if (!disposedValue) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig); ResetConfigMechanism(); disposedValue = true; } GC.SuppressFinalize(this); } private static void ResetConfigMechanism() { typeof(ConfigurationManager) .GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, 0); typeof(ConfigurationManager) .GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); typeof(ConfigurationManager) .Assembly.GetTypes() .Where(x => x.FullName == "System.Configuration.ClientConfigPaths") .First() .GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); } } }</code>
To permanently change the app.config during the entire runtime:
The above is the detailed content of How to Dynamically Modify the Default app.config at Runtime?. For more information, please follow other related articles on the PHP Chinese website!