修改配置部分会将该部分保存到其他配置文件中

时间:2013-04-04 03:15:48

标签: c# encryption configuration app-config

我有一个带有connectionStrings部分的myapp.somenamespace.exe.config文件,我需要对其进行加密。还有一些我想要完整的其他配置设置。所以我写了这个小工具就可以了:

class Program
{
    static void Main(string[] args)
    {
        EncryptSection("myapp.somenamespace.exe.config", "connectionStrings");
    }
    static void EncryptSection(string fileName, string sectionName)
    {
        var config = ConfigurationManager.OpenExeConfiguration(fileName);

        var section = config.GetSection(sectionName);

        if (section.SectionInformation.IsProtected) return;

        secction.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");

        config.Save();
    }
}

会发生什么,它会创建一个名为myapp.somenamespace.exe.config.config的新配置文件 - 添加一个重复的.config扩展名,其中只包含加密的部分。它修改原始配置文件。

为什么会出现这种奇怪的行为以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

更改此行:

EncryptSection("myapp.somenamespace.exe.config", "connectionStrings");

到此:

EncryptSection("myapp.somenamespace.exe", "connectionStrings");

the documentation on MSDN声明第一个参数实际上是he path of the executable (exe) file,因此它会在.config期间增加Save