更新xml文件中的元素值
本文关键字:元素 xml 文件 更新 | 更新日期: 2023-09-27 18:05:25
我正在更新一个xml文件,
public static void UpdateDesignCfg(string ChildName, string[,] AttribWithValue)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load("DesignCfg.xml");
XmlElement formData = (XmlElement)doc.SelectSingleNode("//" + ChildName);
if (formData != null)
{
for (int i = 0; i < AttribWithValue.GetLength(0); i++)
{
formData.SetAttribute(AttribWithValue[i, 0], AttribWithValue[i, 1]);
}
}
doc.Save("DesignCfg.xml");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
但是我经常得到这个错误(不是每次)
the process cannot access the file because it is being used by another process
那么,有没有办法在每次更改后"释放"文件呢?
UPDATE
文件从另一个地方被访问并且没有被关闭。在其他地方使用相同的Load
方法
我解决了我的问题,非常感谢@Ulugbek Umirov的帮助,问题是在我的ReadXmlFile方法上,它是这样的:
public static Color GetColor(string ChildName, string Attribute)
{
Color clr = new Color(); string v = "";
XmlTextReader reader = new XmlTextReader("DesignCfg.xml");
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
if (chldNode.Name == ChildName)
v = chldNode.Attributes["" + Attribute + ""].Value;
}
clr = System.Drawing.ColorTranslator.FromHtml(v);
return clr;
}
,新的是:
public static Color GetColor(string ChildName, string Attribute)
{
Color clr = new Color();
string v = "";
XmlDocument doc = new XmlDocument();
doc.Load("DesignCfg.xml");
XmlElement formData = (XmlElement)doc.SelectSingleNode("//" + ChildName);
if (formData != null)
v = formData.GetAttribute(Attribute);
clr = System.Drawing.ColorTranslator.FromHtml(v);
return clr;
}
谢谢大家的帮助