How to Write to a User.Config file through ConfigurationManager?

Josh G picture Josh G · Apr 13, 2010 · Viewed 11.3k times · Source

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.

Answer

Jay picture Jay · Apr 13, 2010

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.