加密配置部分
我正在尝试以编程方式加密 App.config 和 Web.config 文件的配置部分。在下面的代码中,我在 configFilePath 变量中设置了要编辑的路径配置文件,然后期望它加密 connectionStrings 部分。
var config = ConfigurationManager.OpenExeConfiguration(configFilePath); varsection = config.GetSection(“connectionStrings”); if (section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); section.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings"); } section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); section.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings");
这运行良好,没有任何错误,但不会对给定文件进行任何更改。就好像它并没有真正访问我想要访问的文件。
有什么想法吗?
I'm trying to programmatically encrypt configuration sections of App.config and Web.config files. In the following code, I set the path configuration file I want to edit in the configFilePath variable and then expect it to encrypt the connectionStrings section.
var config = ConfigurationManager.OpenExeConfiguration(configFilePath); var section = config.GetSection("connectionStrings"); if (section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); section.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings"); } section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); section.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings");
This runs fine without any errors but makes no changes to the given file. It's like it's not really accessing the file I want to access.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,回答我自己的问题...
代码确实没有打开正确的配置文件。为此,我们需要使用
ConfigurationManager.OpenMappedExeConfiguration()
而不是ConfigurationManager.OpenExeConfiguration()
。因此,上面代码的第一行改为:
Right, answering my own question...
The code was indeed not opening the right config file. To do that we need to use
ConfigurationManager.OpenMappedExeConfiguration()
instead ofConfigurationManager.OpenExeConfiguration()
.So, the first line of the code above changes to: