How to Modify Configuration through Code

Topics: Building and extending application blocks, Enterprise Library Core, General discussion
Sep 18, 2007 at 7:45 AM

I want to modify the configuration section programtically and I attempted like that:

IConfigurationSource s = ConfigurationSourceFactory.Create();
MySettings dms = MySettings.GetMySettings(s);
dms.Loading.BulkUploadingEnabled = true;

MySettings is my custom configuration section in configuration file. But error throws in last line when I set the value of Loading.BulkUpLoadingEnabled to true. Error: The configuration is readonly.

Please tell me the work around. One thing I have to consider is that configuration file for this section may be a separate file or may be included in application.exe.config file.

Zeeshan Gulzar
Sep 18, 2007 at 2:11 PM

You can't modify configuration information retrieved from a configuration source. What you can do is to specify a new configuration section to override the existing settings in the configuration file, and wait until the configuration information is reloaded. Please look at method void Add(IConfigurationParameter saveParameter, string sectionName, ConfigurationSection configurationSection) in the IConfigurationSource interface.

Sep 19, 2007 at 7:20 AM
Thanks Fernando,

Exception is being thrown at line 6 InvalidOperationException "Cannot add a ConfigurationSection that already belongs to the Configuration.":

1 string fileName = Application.ExecutablePath + ".config";
2 FileConfigurationParameter param = new FileConfigurationParameter(fileName);
3 FileConfigurationSource fs = new FileConfigurationSource(fileName);
4 MySettings dms = MySettings.GetMySettings(fs);
5 dms.Loading.BulkUploadingEnabled = true;
6 fs.Save(fileName,"MyConfiguration", dms);

I also tried to first call Remove and then Add but Remove method works fine and remove section from config file but when Add method called, same exception is thrown.

Please Help.

Zeeshan Gulzar
Sep 19, 2007 at 12:38 PM
Hi Zeeshan,

You can only add a new configuration section, not one that you got from existing configuration. This means you'll have to copy all the configuration information to this new instance.
Removing shouldn't be necessary.