如何通过ConfigurationManager写入User.Config文件?

我正在尝试使用ConfigurationManager将用户设置保留到配置文件中。

我想将这些设置仅限于用户,因为在没有管理员权限的情况下,无法在Vista / Win 7上保存应用程序更改。

这似乎让我得到了用户的配置,它似乎保存在Win 7中([Drive]:\ Users \ [Username] \ AppData \ Local \ [ApplicationName] \ [AssemblyName] [hash] \ [Version \]

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

每当我尝试将任何更改保存到此配置时,我都会遇到以下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) 

我尝试将自定义ConfigurationSection添加到此配置中。 我已经尝试添加到AppSettingsSection。 每当我调用config.Save()它都抛出上面的exception。

有任何想法吗?

我尝试通过Project-> Settings设计器使用ApplicationSettingsBase类,但似乎不能保存自定义类型。 我想要类似的function,能够保存自定义类型。

您需要为该部分设置SectionInformation.AllowExeDefinition值:

  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(); } 

默认值为ConfigurationAllowExeDefinition.MachineToApplication,它只允许将该部分放在machine.config和app.exe.config上。