如标题中所述,我很难更改从自定义 user.config 获取的 NameValueCollection 的值。出于某种原因,每当我尝试使用 SET 方法或 ADD/REMOVE 方法更改值时,它都会抛出异常并通知我该集合是只读的,我也使用 app.config 尝试过,但它的结果相同,但是如果我将其编辑为 XML 元素,然后通过 ChildNodes 则它可以工作。任何帮助深表感谢。这是我的代码:
用户配置:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="users_fächer" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<users_faecher>
<add key="user1" value="value1" />
<add key="user2" value="value2" />
</users_faecher>
</configuration>
执行:
string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Users.config");
string new_fächer = input[1];
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = dir;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
ConfigurationSection myParamsSection = config.GetSection("users_faecher");
string myParamsSectionRawXml = myParamsSection.SectionInformation.GetRawXml();
XmlDocument sectionXmlDoc = new XmlDocument();
sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml));
NameValueSectionHandler handler = new NameValueSectionHandler();
NameValueCollection users_fächer = handler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;
users_fächer.Set(user, new_fächer);
config.Save(ConfigurationSaveMode.Modified, true);