Unrecognized attribute 'configProtectionProvider' after encrypting app.config

I managed to get Rick Schott's answer working, with one important caveat - you cannot use the static version of ConfigurationManager.GetSection to retrieve the section after the refresh - you have to use Configuration.GetSection instead.

Full code:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection section = config.GetSection("passwordSection") as ConfigurationSection;

if (!section.SectionInformation.IsProtected)
{
    // Encrypt the section.
    section.SectionInformation.ProtectSection("DPAPIProtection");
    section.SectionInformation.ForceSave = true;
    config.Save(ConfigurationSaveMode.Modified);

    // The passwords are now encrypted.
    // Refresh the *parent* of the section that your passwords are in.
    ConfigurationManager.RefreshSection("configuration");

    // Now use Configuration.GetManager to retrieve the new password section.
    // This doesn't throw the Configuration Exception :)
    ConfigurationSection section2 = config.GetSection("passwordSection") as ConfigurationSection;
}

According to this blog post, the fix is to call RefreshSection() on the parent:

RefreshSection("applicationSettings")

Unrecognized attribute configProtectionProvider


I found this: http://andybrennan.wordpress.com/2014/06/05/unrecognized-attribute-configprotectionprovider-after-encrypting-app-config/. And it's solves the problem.

Just use this method as written on the blog:

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

Invoke it after save/refresh the config.