尝试使用NameValueCollection更改值时,C#Collection是只读异常

时间:2017-03-15 14:21:22

标签: c# xml config namevaluecollection

如标题中所述,我很难更改从自定义user.config获取的NameValueCollection的值。出于某种原因,每当我尝试使用SET方法或ADD / REMOVE方法更改值时,它会抛出异常并通知我该集合是只读的我也尝试过使用app.config但是它的结果相同,但如果我将其编辑为XML ELement然后通过ChildNodes,那么它的工作原理。任何帮助深表感谢。这是我的代码:

user.config:

<?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);

0 个答案:

没有答案