[英]C# XMLDocument Save - Process cannot access the file because it is being used by another process
在调用load之后,我无法保存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);
对我来说,这是由于文件被写入一个包含许多(100k)其他文件的目录。 一旦我清除了所有其他文件,问题便消失了。 NTFS似乎在单个文件夹中存在非常大量的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.