c# – 加密app.config后无法识别的属性’configProtectionProvider’

前端之家收集整理的这篇文章主要介绍了c# – 加密app.config后无法识别的属性’configProtectionProvider’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的应用程序开始时运行以下方法传递一个生活在applicationSettings下的部分:
  1. public static void EncryptConfigSection(string sectionKey)
  2. {
  3. Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  4. ConfigurationSection section = config.GetSection(sectionKey);
  5. if (section != null)
  6. {
  7. if (!section.SectionInformation.IsProtected)
  8. {
  9. if (!section.ElementInformation.IsLocked)
  10. {
  11. section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
  12. section.SectionInformation.ForceSave = true;
  13. config.Save(ConfigurationSaveMode.Full);
  14. ConfigurationManager.RefreshSection(sectionKey);
  15. }
  16. }
  17. }
  18. }

以下是app.config中该部分的示例:

  1. <applicationSettings>
  2. <Example.Properties.Settings>
  3. <setting name="Key" serializeAs="String">
  4. <value>Value</value>
  5. </setting>
  6. </Example.Properties.Settings>
  7. </applicationSettings>

当我尝试访问该部分中的任何设置时,我收到以下错误

Unrecognized attribute ‘configProtectionProvider’

这是一个桌面应用程序,需要在启动时加密某些设置,然后在退出时解密.

有没有人有这个问题的解决方案?

解决方法

我发现了这个: http://andybrennan.wordpress.com/2014/06/05/unrecognized-attribute-configprotectionprovider-after-encrypting-app-config/.它解决了这个问题.

只需使用博客上写的这个方法

  1. private void ResetConfigMechanism()
  2. {
  3. typeof(ConfigurationManager)
  4. .GetField("s_initState",BindingFlags.NonPublic |
  5. BindingFlags.Static)
  6. .SetValue(null,0);
  7.  
  8. typeof(ConfigurationManager)
  9. .GetField("s_configSystem",BindingFlags.NonPublic |
  10. BindingFlags.Static)
  11. .SetValue(null,null);
  12.  
  13. typeof(ConfigurationManager)
  14. .Assembly.GetTypes()
  15. .Where(x => x.FullName ==
  16. "System.Configuration.ClientConfigPaths")
  17. .First()
  18. .GetField("s_current",BindingFlags.NonPublic |
  19. BindingFlags.Static)
  20. .SetValue(null,null);
  21. }

保存/刷新配置后调用它.

猜你在找的C#相关文章