.NET 2.0中是否有任何支持的API用于写入主exe的.config文件的userSettings部分?
场景是:
Winforms 2.0应用程序.
我有一个具有用户级别范围的设置(数据库连接字符串,如果您需要知道).这意味着当用户保存设置的值时,每个用户都有.net创建的user.config文件.
对于第一次运行应用程序的新用户,应用程序的主exe .config文件在用户设置部分中包含默认值.在项目属性的“设置”选项卡中创建设置时,此部分由visual studio创建.
现在,我想允许计算机中的任何管理员用户能够更改新用户的默认值.只有管理员才有此选项,因为普通用户无权写入主exe的.config文件.
我已经找到了如何将用户设置写入用户的.config文件,以及如何写入主.config文件的appSettings部分.但是当我试图找出如何写入主.config的userSettings部分时,我的谷歌搜索失败了
我唯一的机会是失败回System.Xml并在XmlDocument中手动加载.config吗?
解决方法
经过一番研究,我想出了这个解决方案.它有点低级,但仍然可以通过.NET配置API而无需手动解析.config文件.
- static void SaveUserSettingDefault(string clientSectionName,string settingName,object settingValue)
- {
- System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- // find section group
- ConfigurationSectionGroup group = config.SectionGroups[@"userSettings"];
- if (group == null) return;
- // find client section
- ClientSettingsSection clientSection = group.Sections[clientSectionName] as ClientSettingsSection;
- if (clientSection == null) return;
- // find setting element
- SettingElement settingElement = null;
- foreach (SettingElement s in clientSection.Settings)
- {
- if (s.Name == settingName)
- {
- settingElement = s;
- break;
- }
- }
- if (settingElement == null) return;
- // remove the current value
- clientSection.Settings.Remove(settingElement);
- // change the value
- settingElement.Value.ValueXml.InnerText = settingValue.ToString();
- // add the setting
- clientSection.Settings.Add(settingElement);
- // save changes
- config.Save(ConfigurationSaveMode.Full);
- }
给定一个包含以下内容的.config:
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <configSections>
- <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup,System,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" >
- <section name="MyAssembly.Properties.Settings" type="System.Configuration.ClientSettingsSection,PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
- </sectionGroup>
- </configSections>
- <userSettings>
- <MyAssembly.Properties.Settings>
- <setting name="sqlConnectionString" serializeAs="String">
- <value>Server=(local);Database=myDatabase;Integrated Security=true;</value>
- </setting>
- </MyAssembly.Properties.Settings>
- </userSettings>
- </configuration>
你会像这样使用它: