如何撰写通过ConfigurationManager的一个User.Config文件? [英] How to Write to a User.Config file through ConfigurationManager?
问题描述
我试图保持用户设置使用ConfigurationManager中的配置文件。
I'm trying to persist user settings to a configuration file using ConfigurationManager.
我想这些范围设置,只有用户,因为应用程序的更改不能保存在Vista / Win 7的没有管理员权限。
I want to scope these settings to the user only, because application changes can't be saved on Vista/Win 7 without admin privileges.
这似乎让我的用户的配置,这似乎在这里保存在Win 7([驱动器]:\用户\ [用户名] \应用程序数据\本地\ [应用程序名称] \ [的AssemblyName] [散列] \ [版本\)
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)
我曾尝试添加自定义配置节这一配置。我曾尝试加入到AppSettingsSection。每当我称之为 config.Save()
它抛出上述异常。
任何想法?
我想从项目 - >设置设计师使用ApplicationSettingsBase类,但它不会出现,你可以保存自定义类型与此有关。我想类似的功能,能够保存自定义类型的能力。
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值的部分:
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();
}
默认值为ConfigurationAllowExeDefinition.MachineToApplication只允许上放置的machine.config和app.exe.config节
The default value is ConfigurationAllowExeDefinition.MachineToApplication which allows only to place the section on machine.config and app.exe.config.
这篇关于如何撰写通过ConfigurationManager的一个User.Config文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!