如何写入主exe的.config userSettings部分?

.NET 2.0中是否有支持的API用于写入 主exe的.config文件userSettings部分?

场景是:

Winforms 2.0应用程序。

我有一个具有用户级别范围的设置(数据库连接字符串,如果您需要知道)。 这意味着当用户保存设置的值时,每个用户都有.net创建的用户 .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:

     
Server=(local);Database=myDatabase;Integrated Security=true;

你会像这样使用它:

 if (RunningAsAdmin) // save value in main exe's config file { SaveUserSettingDefault(@"MyAssembly.Properties.Settings", @"SQLConnectionString", theNewConnectionString); } else // save setting in user's config file { Settings.Default. SQLConnectionString = theNewConnectionString; Settings.Default.Save(); } 

我想是的 – 手动写入.config文件是唯一的方法。 或者您可以让管理员自己编辑.config文件。