一千萬個為什麽

搜索

如何通過ConfigurationManager寫入User.Config文件?

我正在嘗試使用ConfigurationManager將用戶設置保留到配置文件中。

我想將這些設置僅限於用戶,因為在沒有管理員權限的情況下,無法在Vista/Win 7上保存應用程序更改。

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

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

每當我嘗試將任何更改保存到此配置時,我都會遇到以下異常:

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()時,它都會拋出上面的異常。

有任何想法嗎?

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.

最佳答案

您需要為該部分設置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上。

轉載註明原文: 如何通過ConfigurationManager寫入User.Config文件?