Set ConfigurationManager Values

--

Have you ever needed to set a value in ConfigurationManager.AppSettings e.g. ConfigurationManager.AppSettings.Add("foo", "value") ?

Perhaps because you need to test some code that relies on retrieving values directly from the ConfigurationManager, or whatever reason, I’m not judging.

And then you try it, but it doesn’t work?

Well, look no further …

public static class TestConfiguration
{
public static ConnectionStringSettingsCollection Set(this ConnectionStringSettingsCollection settings, string key, string value)
{
var element = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
var collection = typeof(ConfigurationElementCollection).GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

element?.SetValue(settings, false);
collection?.SetValue(settings, false);

settings.Add(new ConnectionStringSettings(key, value));

collection?.SetValue(settings, true);
element?.SetValue(settings, true);

return settings;
}
}

Now, you will be able to call:

ConfigurationManager.AppSettings.Set("foo", "value");

and it will actually work.

Have fun!

--

--

Ikechi Michael

I’ve learned I don’t know anything. I've also learned that people will pay for what I know. Maybe that's why they never pay.