使用 XmlDocument Open XML 文件后直接抛出异常

Issue with XmlDocument Open XML file directly after using throws exception

我的 XmlDocument 有一个奇怪的问题 class。

我用它写了一些 XML 文件,效果很好。 我有 Save() 方法:

public void Save()
{
    var xwSettings = new XmlWriterSettings
    {
        Encoding = new UTF8Encoding(false),
        Indent = true,
        IndentChars = "\t"
    };
    using (XmlWriter xw = XmlWriter.Create(new FileStream(this.FilePath, FileMode.Create), xwSettings))
    {
        XmlDocument.WriteTo(xw);
    }
}

就像大家看到的那样,我正在使用 "using",这应该免费提供 xml :) 但是,如果我在调用 Save() 后尝试直接读取此文件,则会出现异常:

The process can not access the file "___.xml", because it's already in use by another process.

有人可以向我解释一下并给我一个解决方案吗?

亲切的问候

您没有处理文件流。尝试像这样更改您的代码。

        using (var xmlStream = new FileStream(this.FilePath, FileMode.Create))
        {
            using (XmlWriter xw = XmlWriter.Create(xmlStream, xwSettings))
            {
                var xDoc = new XmlDocument();
                xDoc.WriteTo(xw);
            }
        }