Unrecognized attribute ‘configProtectionProvider’ after encrypting app.config

This little problem had been driving me crazy.

I had some code to encrypt a config as part of the start up of a service I was working on, but immediately afterwards I had an exception thrown stating “Unrecognized attribute ‘configProtectionProvider’ after encrypting app.config”.

Stopping and starting the service seemed to fix this and I would never see the problem again. Of course this was unexpected behaviour and our testers picked up on it straight away and asked me to get rid of the problem as it created an unexpected entry in the event log.

It seems that you can save and refresh the config as much as you like – it doesn’t actually reset it properly in memory. It turns out the only way to fully reset it is to use reflection and forcefully set a few things to null as such:

private 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);
    }

 

I hope you find this more quickly than I did and it saves you some frustration 🙂

5 thoughts on “Unrecognized attribute ‘configProtectionProvider’ after encrypting app.config

Leave a comment