我正在通过此代码更新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
所以,有没有办法在每次更改后“释放”文件?
答案 0 :(得分:3)
<强>更新强>
该文件可从其他地方访问,但未关闭。在其他地方使用相同的Load
方法。
答案 1 :(得分:1)
我解决了我的问题,非常感谢@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;
}
谢谢大家的帮助:)