【问题标题】:Overwrite encrypted configuration section without decrypting?覆盖加密的配置部分而不解密?
【发布时间】:2015-01-03 01:00:28
【问题描述】:

当我尝试访问已加密且无法正确解密的配置部分时(例如,有人只是盲目地从另一台机器上抓取配置文件)-Configuration 类抛出异常。我想抓住这种情况并在这种情况下完全重写该部分。

我已尝试删除并重新添加有问题的部分,但似乎忽略了删除 - 'catch' 中的第二条语句引发了另一个关于该部分已存在的异常:

try
{
    // this getter might throw an exception - e.g. if encrypted on another machine
    var connStrings = config.ConnectionStrings;
}
catch (ConfigurationException)
{
    config.Sections.Remove("connectionStrings");
    config.Sections.Add("connectionStrings", new ConnectionStringsSection());
}

这可能与我的 connectionStrings 部分位于单独的文件中这一事实有关,即我的配置文件有类似 <connectionStrings configSource="connections.config"/> 的内容,而实际加密的内容在 connections.config 文件中。

是否有可能只使用 .NET 配置类来完成我需要的操作而无需退回到直接的 XML 操作?

【问题讨论】:

    标签: c# .net configurationmanager


    【解决方案1】:

    我很确定这会满足您的需求。就我而言,我只是包含了一个虚假的 connectionString 设置:

    <connectionStrings>
        <add connectionString="foo"/>
    </connectionStrings>
    

    我没有包含“名称”属性,因此尝试读取 ConnectionStrings 会爆炸,就像您的情况一样:

    try {
        var x = ConfigurationManager.ConnectionStrings;   //blows up             
    }
    catch {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.Sections.Remove("connectionStrings");
        config.Save(); //Now save the changes
        ConfigurationManager.RefreshSection("connectionStrings"); //and reload the section
        var x = ConfigurationManager.ConnectionStrings; //can now read!                
    }
    

    你仍然不能这样做:

    config.Sections.Add("connectionStrings", new ConnectionStringsSection());
    

    因为(至少在我的机器上),它从 Machine.config 中获取连接字符串。

    我怀疑在你的情况下这很好。现在,如果您愿意,您可以添加自己的连接字符串,而您实际上并不需要完全删除连接字符串部分。

    【讨论】:

    • 谢谢!实际上,我忘记了连接字符串也是从机器配置中提取的。否则我的config.Sections.Remove("connectionStrings"); 工作得很好。无需保存一次或刷新。至少,在我的情况下,它可以在没有这些行的情况下工作。但无论如何,谢谢,你的回答让我走上了正确的道路:)
    • 哦。诡异的。是的,就我而言,我确实需要这两行。
    • 在我的情况下,它不是运行应用程序的配置,只是通过ConfigurationManager.OpenExeConfiguration(executablePath) 为其他 exe 加载的配置。也许这就是原因……
    猜你喜欢
    • 2017-02-24
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2011-12-24
    • 2010-12-01
    • 2011-12-30
    相关资源
    最近更新 更多