我在我的应用程序开始时运行以下方法传递一个生活在applicationSettings下的部分:
- public static void EncryptConfigSection(string sectionKey)
- {
- Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- ConfigurationSection section = config.GetSection(sectionKey);
- if (section != null)
- {
- if (!section.SectionInformation.IsProtected)
- {
- if (!section.ElementInformation.IsLocked)
- {
- section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
- section.SectionInformation.ForceSave = true;
- config.Save(ConfigurationSaveMode.Full);
- ConfigurationManager.RefreshSection(sectionKey);
- }
- }
- }
- }
以下是app.config中该部分的示例:
- <applicationSettings>
- <Example.Properties.Settings>
- <setting name="Key" serializeAs="String">
- <value>Value</value>
- </setting>
- </Example.Properties.Settings>
- </applicationSettings>
当我尝试访问该部分中的任何设置时,我收到以下错误:
Unrecognized attribute ‘configProtectionProvider’
这是一个桌面应用程序,需要在启动时加密某些设置,然后在退出时解密.
有没有人有这个问题的解决方案?
解决方法
我发现了这个:
http://andybrennan.wordpress.com/2014/06/05/unrecognized-attribute-configprotectionprovider-after-encrypting-app-config/.它解决了这个问题.
- 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);
- }
保存/刷新配置后调用它.