你好,我有在app.exe.config文件中创建/更新字段的功能
public static void UpdateConfig(string FieldName, string FieldValue, ConfigSelector SectionName = ConfigSelector.AppSettings)
{
switch (SectionName)
{
case ConfigSelector.Execption:
{
// MessageBox.Show("gg");
var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
if (xmlDoc.SelectSingleNode("configuration/Execption") != null)
{
if (xmlDoc.SelectSingleNode("configuration/Execption/List") != null)
{
// create new node <add key="Region" value="Canterbury" />
var nodeRegion = xmlDoc.CreateElement("add");
nodeRegion.SetAttribute("key", FieldName);
nodeRegion.SetAttribute("value", FieldValue);
xmlDoc.SelectSingleNode("configuration/Execption/List").AppendChild(nodeRegion);
}
else
{
var List = xmlDoc.CreateElement("List");
xmlDoc.SelectSingleNode("configuration/Execption").AppendChild(List);
UpdateConfig(FieldName, FieldValue, SectionName);
}
}
else
{
var List = xmlDoc.CreateElement("Execption");
xmlDoc.SelectSingleNode("configuration").AppendChild(List);
UpdateConfig(FieldName, FieldValue, SectionName);
}
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("Execption/List");
break;
}
}
}函数首先检查是否存在xpath配置/执行,如果不存在,则创建该路径并再次调用函数,如果不存在,则第二次检查配置/执行/列表路径是否存在,如果不存在,则创建路径并再次调用函数,第三次添加必填字段,即fieldname和fieldvalue,
但我让System.StackOverflowException排好队:
if (xmlDoc.SelectSingleNode("configuration/Execption") != null)我错过了什么吗?
发布于 2018-08-02 21:11:21
添加新元素后不保存文档,因此当您在下一次迭代中加载文件时,新元素不在那里,xmlDoc.SelectSingleNode("configuration/Execption") != null仍然为false,因此代码在无限递归中再次创建该元素,您将得到StackOverflowException。
只需在更改文档后将其保存
else
{
var List = xmlDoc.CreateElement("Execption");
xmlDoc.SelectSingleNode("configuration").AppendChild(List);
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
UpdateConfig(FieldName, FieldValue, SectionName);
}发布于 2018-08-02 21:10:58
您正在递归调用UpdateConfig,并且已经向其传递了完全相同的参数
UpdateConfig(FieldName, FieldValue, SectionName);因为递归调用发生在xmlDoc.Save()之前,所以它总是在相同的内容上工作。
在执行递归调用之前保存应该可以解决这个问题。
https://stackoverflow.com/questions/51654327
复制相似问题