我在调用加载后无法保存我的 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);
}
}
如有任何帮助,我们将不胜感激。
最佳答案
当您尝试保存时,您创建的 XmlReader
仍处于打开状态,因此它会锁定文件并阻止保存。
一旦加载到 XmlDocument
中,您就不再需要阅读器了,因此您可以在尝试保存之前关闭/处置它,然后保存应该会起作用。
例如:
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;
XmlDocument file = new XmlDocument();
using (XmlReader reader = XmlReader.Create(filePath, readerSettings))
file.Load(reader);
/* do work with xml document */
if (save)
file.Save(filePath);
关于C# XMLDocument Save - 进程无法访问该文件,因为它正被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34772875/