views:

411

answers:

2

I'm trying to persist user settings to a configuration file using ConfigurationManager.

I want to scope these settings to the user only, because application changes can't be saved on Vista/Win 7 without admin privileges.

This seems to get me the user's configuration, which appears to be saved here in Win 7 ([Drive]:\Users\[Username]\AppData\Local\[ApplicationName]\[AssemblyName][hash]\[Version\)

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);

Whenever I try to save any changes at all to this config I get this exception:

InnerException: System.InvalidOperationException
Message="ConfigurationSection properties cannot be edited when locked."
Source="System.Configuration"
StackTrace:
    at System.Configuration.SectionInformation.VerifyIsEditable()
    at System.Configuration.MgmtConfigurationRecord.GetConfigDefinitionUpdates(Boolean requireUpdates, ConfigurationSaveMode saveMode, Boolean forceSaveAll, ConfigDefinitionUpdates& definitionUpdates, ArrayList& configSourceUpdates)

I have tried adding a custom ConfigurationSection to this config. I have tried adding to the AppSettingsSection. Whenever I call config.Save() it throws the exception above.

Any ideas?

I tried using the ApplicationSettingsBase class through the Project->Settings designer, but it doesn't appear that you can save custom types with this. I want similar functionality with the ability to save custom types.

Thanks.

A: 

You can see an example of performing this here: http://csharptest.net/?p=300

The source is available at: http://code.google.com/p/csharptest-net/source/browse/trunk/src/Library#Library/AppConfig

csharptest.net
I'm not really looking for a library solution right now. I may look through the library code to try to distill the fix.
Josh G
+1  A: 

Below is a possible answer from MSDN forums:

You need to set the SectionInformation.AllowExeDefinition value for the section:

 Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
UserSettings settings;
if ((settings = (UserSettings)configuration.Sections[GENERAL_USER_SETTINGS]) == null)
{
      settings = new UserSettings();
      settings.SectionInformation.AllowExeDefinition =   
                 ConfigurationAllowExeDefinition.MachineToLocalUser;
      configuration.Sections.Add(GENERAL_USER_SETTINGS, settings);
      configuration.Save();
}

The default value is ConfigurationAllowExeDefinition.MachineToApplication which allows only to place the section on machine.config and app.exe.config.
Jay
I'll try that. I tried setting the AllowExeDefinition property once and caused the same exception that config.Save() fired off. I'll copy this code segment and try again.
Josh G
It appears I needed to set the AllowExeDefinition BEFORE adding the section and saving the changes for the first time. Now everything appears to be working fine.
Josh G