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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-17 18:54:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/2632806/how-to-write-to-a-user-config-file-through-configurationmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!