问题描述
希望我能得到一些帮助来解决一个我似乎无法在任何地方找到明确答案的令人恼火的问题.
Hoping I might be able to get some help with an infuriating problem which I can't seem to find a definitive answer for anywhere.
我使用 XDocument 对象将数据附加到 xml 文档,然后使用 xDoc.save(path) 覆盖现有文件,但由于某种原因,我第一次运行代码时会抛出错误,即使文件是未被任何其他进程使用.
I am appending data to an xml document using an XDocument object, and then overwriting the existing file using xDoc.save(path), but for some reason the first time I run the code an error is thrown even though the file is not in use by any other process.
*进程无法访问文件C:\XXX\XXXX\Telemetry\2011_11_22.tlm,因为它正被另一个进程使用."*
*"The process cannot access the file "C:\XXX\XXXX\Telemetry\2011_11_22.tlm because it is being used by another process."*
后续迭代不会导致问题.
Subsequent iterations do not cause a problem.
这是我使用的代码,删除了 try/catch 以提高可读性:-
Here is my code that I am using with try/catch removed for readability:-
XElement x = GenerateTelemetryNode(h); //Create a new element to append
if (File.Exists(path))
{
if (xDoc == null)
{
xDoc = XDocument.Load(new StreamReader(path));
}
}
else
{
xDoc = new XDocument();
xDoc.Add(new XElement("TSD"));
}
xDoc.Element("TSD").Add(x);
xmlPath = path;
xDoc.Save(path);
我相信对此有一个非常简单的解释.
I'm sure there's a very simple explanation for it.
非常感谢您的回复.
推荐答案
我预计问题是 StreamReader 尚未处理,在这种情况下,它仍将附加到文档中.我建议将 StreamReader 创建包装在 using
子句中,以确保在加载文档后立即处理:
I would expect the problem is the StreamReader hasn't been disposed in which case it will still be attached to the document. I would suggest using wrapping the StreamReader creation in a using
clause to ensure that is disposed of immediately after the document has been loaded:
if (xDoc == null)
{
using (var sr = new StreamReader(path))
{
xDoc = XDocument.Load(new StreamReader(sr));
}
}
这篇关于XDocument.Save() 无法访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!