简体   繁体   中英

Protecting Section in App.config file Console Application

I am trying to encrypt the appSettings and connectionStrings section in App.config file of the console application. For some reason section.SectionInformation.IsProtected is always returning true.

static void Main(string[] args)
{
    EncryptSection("connectionStrings", "DataProtectionConfigurationProvider"); 
}

private static void EncryptSection(string sectionName, string providerName)
{
    string assemblyPath = Assembly.GetExecutingAssembly().Location;
    Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyPath);

    ConfigurationSection section = config.GetSection(sectionName);

    if (section != null && !section.SectionInformation.IsProtected)
    {
        section.SectionInformation.ProtectSection(providerName);
        config.Save(); 
    }
}

Not sure why it is always returning true.

Your code opens the current application configuration. You can try this :

static void Main(string[] args)
{
    if (args.Length != 0)
    {
        Console.Error.WriteLine("Usage : Program.exe <configFileName>"); // App.Config
    }
    EncryptSection(args[0], "connectionStrings", "DataProtectionConfigurationProvider");
}

private static void EncryptSection(string configurationFile, string sectionName, string providerName)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(configurationFile);
    ConfigurationSection section = config.GetSection(sectionName);

    if (section != null && !section.SectionInformation.IsProtected)
    {
        section.SectionInformation.ProtectSection(providerName);
        config.Save();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM