Skip to content

Instantly share code, notes, and snippets.

@xtrmstep
Created October 1, 2015 13:27
Show Gist options
  • Save xtrmstep/67ac72018efaa6370d7a to your computer and use it in GitHub Desktop.
Save xtrmstep/67ac72018efaa6370d7a to your computer and use it in GitHub Desktop.
The hack for substitution of standard configuration file
/// <summary>
/// The hack for substitution of standard configuration file
/// question at StackOweflow: http://stackoverflow.com/questions/6150644/change-default-app-config-at-runtime
/// a solution: http://stackoverflow.com/a/6151688/2833774
/// </summary>
public abstract class AppConfigChanger : IDisposable
{
public static AppConfigChanger Change(string path)
{
return new AppConfigSubstitutor(path);
}
public abstract void Dispose();
private class AppConfigSubstitutor : AppConfigChanger
{
private readonly string _oldConfig = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
private bool _disposedValue;
public AppConfigSubstitutor(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()
{
var initState = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
if (initState == null) return;
initState.SetValue(null, 0);
var configSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static);
if (configSystem == null) return;
configSystem.SetValue(null, null);
var clientConfigPaths = typeof(ConfigurationManager).Assembly.GetTypes().Where(x => x.FullName == "System.Configuration.ClientConfigPaths");
var clientConfigPath = clientConfigPaths.First().GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static);
if (clientConfigPath == null) return;
clientConfigPath.SetValue(null, null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment