あなたは、フレームワークの周りハッキング気にしないと、あなたは合理的に、あなたはこのような何かを試みることができる(すなわち、それは、Webアプリケーションやイントラネット・アプリケーションの)アプリケーションが実行されている.NET Frameworkのバージョンをとることができる場合は、次の
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!");
}
}
私的反射...非常にいたずら。 –
.netフレームワークのバージョンは上記の例とは特に関係がありますか?つまり、私は似たような例を試していますが、SetValueが値を設定しているように見えますが、コンフィギュレーション設定を取得しようとすると失敗します。つまり、上記のコードがうまくいかない場合があります。ありがとうございました –
's_configSystem'プライベートフィールドは' ConfigurationManager'の実装の詳細で、将来のフレームワークリリースで変更されるかもしれませんし、まったく存在しないかもしれません(例えばmonoは[configSystem](https:// github。 com/mono/mono/blob/effa4c07ba850bedbe1ff54b2a5df281c058ebcb/mcs/class/System.Configuration/System.Configuration/ConfigurationManager.cs#L48)。 –