azamsharp
azamsharp

Reputation: 20066

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.

Upvotes: 6

Views: 4641

Answers (1)

mathieu
mathieu

Reputation: 31202

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();
    }
}

Upvotes: 2

Related Questions