1

I'm trying to programmatically encrypt configuration sections of App.config and Web.config files. In the following code, I set the path configuration file I want to edit in the configFilePath variable and then expect it to encrypt the connectionStrings section.

 var config = ConfigurationManager.OpenExeConfiguration(configFilePath); var section = config.GetSection("connectionStrings"); if (section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); section.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings"); } section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); section.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings"); 

This runs fine without any errors but makes no changes to the given file. It's like it's not really accessing the file I want to access.

Any ideas?

1 Answer 1

1

Right, answering my own question...

The code was indeed not opening the right config file. To do that we need to use ConfigurationManager.OpenMappedExeConfiguration() instead of ConfigurationManager.OpenExeConfiguration().

So, the first line of the code above changes to:

var map = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath }; var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.