Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 391
azamsharp Avatar asked Oct 02 '08 19:10

azamsharp


1 Answers

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();
    }
}
like image 188
mathieu Avatar answered Nov 15 '22 04:11

mathieu