【发布时间】:2016-04-18 19:01:10
【问题描述】:
调用 load.xml 后,我无法保存我的 XML 文件。该函数被调用两次——一次是在“toSave”设置为 false 时,第二次是在设置为 true 时。在第二轮,保存导致异常。我尝试向 XMLReader 添加 Dispose 和 Close 调用,但似乎没有任何帮助。代码如下:
// Check if the file exists
if (File.Exists(filePath))
{
try
{
// Load the file
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;
XmlReader reader = XmlReader.Create(filePath, readerSettings);
XmlDocument file = new XmlDocument();
file.Load(reader);
XmlNodeType type;
type = file.NodeType;
if (toSave)
ModifyXMLContents(file.FirstChild.NextSibling, null);
else
PopulateNode(file.FirstChild.NextSibling, null);
// Save if we need to
if (toSave)
file.Save(filePath);
reader.Dispose();
reader.Close();
}
catch (Exception ex)
{
// exception is: "The process cannot access the file d:\tmp\10.51.15.2\Manifest.xml" because it is being used by another process
Console.WriteLine(ex.Message);
}
}
任何帮助将不胜感激。
【问题讨论】:
-
请勿发布代码图片。复制并粘贴到问题中 - 并非所有用户都可以访问图像,或者他们可能在移动设备上并且无法清楚地看到图像。
-
我建议看看这篇文章,了解如何有效地创建 XML 文档 Other XML Technologies
-
您尝试在关闭阅读器之前保存文件。很可能是读者锁定了文件。在调用
Save之前尝试关闭阅读器(并考虑使用using块)。 -
对不起那个蒂姆。我通常发布代码,但认为这样更容易。干杯
标签: c# xmldocument xmlreader