读取App.Config文件和更改文件,获取空引用异常

时间:2014-12-01 00:32:24

标签: xml app-config

我有以下代码,我试图根据输入到字段中的值来更改app.config文件中的值。我收到的“NullReferenceException”未得到处理'错误,无法弄清楚原因。任何帮助,将不胜感激。谢谢 埃里克 相关代码

    XmlDocument xmlConfig = new XmlDocument();
    xmlConfig.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    string strRegister = txtRegister.Text;
    foreach (XmlElement element in xmlConfig.DocumentElement)
    {
        if (element.Name.Equals("appSettings"))
        {
            foreach (XmlNode node in xmlConfig.ChildNodes)
            {
                if (node.Attributes["key"].Value.Equals("btnTestClick"))
                {
                    if (strRegister.Equals("1"))
                    {
                        node.Attributes["value"].Value = "true";
                    }
                    else if (strRegister.Equals("2"))
                    {
                        node.Attributes["value"].Value = "false";
                    }
                }
            }
        }
    }
    xmlConfig.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    ConfigurationManager.RefreshSection("appSettings");

和app.config内容

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="btnTestClick" value="true"/>
  </appSettings>
</configuration>

1 个答案:

答案 0 :(得分:0)

你可能想在第二个foreach循环中写element.ChildNodes而不是xmlConfig.ChildNodes