Skip to content

Instantly share code, notes, and snippets.

@myaumyau
Created February 18, 2013 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myaumyau/4975059 to your computer and use it in GitHub Desktop.
Save myaumyau/4975059 to your computer and use it in GitHub Desktop.
[C#]ConfigurationManager.AppSettingsの値を書き換え
/*
* ConfigurationManager.AppSettingsの値を書き換え
* http://stackoverflow.com/questions/158783/is-there-a-way-to-override-configurationmanager-appsettings
*/
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Internal;
using System.Reflection;
static class ConfigOverrideTest
{
sealed class ConfigProxy:IInternalConfigSystem
{
readonly IInternalConfigSystem baseconf;
public ConfigProxy(IInternalConfigSystem baseconf)
{
this.baseconf = baseconf;
}
object appsettings;
public object GetSection(string configKey)
{
if(configKey == "appSettings" && this.appsettings != null) return this.appsettings;
object o = baseconf.GetSection(configKey);
if(configKey == "appSettings" && o is NameValueCollection)
{
// create a new collection because the underlying collection is read-only
var cfg = new NameValueCollection((NameValueCollection)o);
// add or replace your settings
cfg["test"] = "Hello world";
o = this.appsettings = cfg;
}
return o;
}
public void RefreshConfig(string sectionName)
{
if(sectionName == "appSettings") appsettings = null;
baseconf.RefreshConfig(sectionName);
}
public bool SupportsUserConfig
{
get { return baseconf.SupportsUserConfig; }
}
}
static void Main()
{
// initialize the ConfigurationManager
object o = ConfigurationManager.AppSettings;
// hack your proxy IInternalConfigSystem into the ConfigurationManager
FieldInfo s_configSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.Static | BindingFlags.NonPublic);
s_configSystem.SetValue(null, new ConfigProxy((IInternalConfigSystem)s_configSystem.GetValue(null)));
// test it
Console.WriteLine(ConfigurationManager.AppSettings["test"] == "Hello world" ? "Success!" : "Failure!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment