为什么我的 XmlWriter 保留其文件流?

som*_*oot 2 .net c# xmlwriter

我编写了一个应用程序,该应用程序有时会写入 XML 文档。后来,创建了一个新对象,并且在代码中的同一部分,XmlWriter无法打开该对象,因为该文件仍在我的程序“使用中”。在寻找答案时,我看到很多线程,答案是CloseOutput在创建 之前设置为 true XmlWriter,并在 using 块中创建它。我已经完成了这两个操作,但仍然遇到这个问题。

XmlWriterSettings xSettings = new XmlWriterSettings();
xSettings.Indent = true;
xSettings.IndentChars = "\t";
xSettings.CloseOutput = true;

using (XmlWriter xWriter = XmlWriter.Create(sOutputFileName, xSettings))
{
    data.WriteContentTo(xWriter);
    xWriter.Close();
}
Run Code Online (Sandbox Code Playgroud)

我有什么明显遗漏的东西吗?

Jon*_*eet 5

我以前也见过类似的事情,也同样感到困惑。看起来您的代码确实在做正确的事情。话虽如此,我现在实际上无法重现该问题。(不过我以前见过……)

除非有人能弄清楚发生了什么,否则我建议的解决方法如下:

var settings = new XmlWriterSettings { Indent = true, IndentChars = "\t" };

using (var stream = File.Create(sOutputFileName))
{
    using (var writer = XmlWriter.Create(stream, settings))
    {
        data.WriteContentTo(writer);
    }
}
Run Code Online (Sandbox Code Playgroud)