【发布时间】:2020-10-24 22:07:29
【问题描述】:
我创建了一个从 XML 文件读取和写入值的程序。当我尝试使用 xmlDoc.Save(path); 保存 XML 时它会抛出异常,因为该文件已被另一个进程使用。
读取方法:
private void ReadXml()
{
//instantiate the xmlDocument
xmlDoc = new XmlDocument();
//declare an XmlNodeList
XmlNodeList xmlNode;
//create a FileStream to read the file
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
//load the file
xmlDoc.Load(fs);
//get all the nodes from the file
xmlNode = xmlDoc.GetElementsByTagName("Drop");
//read all values frome the nodes and save it into variables
for (int i = 0; i <= xmlNode.Count - 1; i++)
{
string name= xmlNode[i].ChildNodes.Item(0).InnerText.Trim();
int DefaultMin= Convert.ToInt32(xmlNode[i].ChildNodes.Item(1).InnerText.Trim());
int DefaultMax = Convert.ToInt32(xmlNode[i].ChildNodes.Item(2).InnerText.Trim());
int min = Convert.ToInt32(xmlNode[i].ChildNodes.Item(3).InnerText.Trim());
int max= Convert.ToInt32(xmlNode[i].ChildNodes.Item(4).InnerText.Trim());
int line= Convert.ToInt32(xmlNode[i].ChildNodes.Item(5).InnerText.Trim());
string lineToChange = xmlNode[i].ChildNodes.Item(6).InnerText;
string filePath = xmlNode[i].ChildNodes.Item(7).InnerText.Trim();
//create the DropItem object
DropItem drop = new DropItem(name, DefaultMin, DefaultMax, line, lineToChange, installPath+filePath);
drop.MinValue = min;
drop.MaxValue = max;
//add the object to the list
drops.Add(drop);
}
}
写法:
public void WriteXml()
{
//declare a xmlNodeList
XmlNodeList xmlNode;
//create a FileStream to read the file
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
//load the file
xmlDoc.Load(fs);
//get all the nodes from the file
xmlNode = xmlDoc.GetElementsByTagName("Drop");
//write the values in the xml
for (int i = 0; i <= drops.Count - 1; i++)
{
xmlNode[i].ChildNodes.Item(3).InnerText=drops[i].MinValue.ToString();
xmlNode[i].ChildNodes.Item(4).InnerText = drops[i].MaxValue.ToString();
}
//save the document
xmlDoc.Save(path);
}
我想我必须在保存之前关闭 read 方法中的 xmlDoc。
【问题讨论】:
-
尝试在每个一次性对象周围添加 using。它还会安全地关闭文件蒸汽。