XmlDocument问题在使用throws异常后直接打开XML文件

时间:2016-02-29 12:34:54

标签: c# xmldocument

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

我用它写了一些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);
    }
}

就像每个人都看到的那样,我正在使用“使用”,这应该给xml免费:) 但是如果我在调用Save()后尝试直接读取这个文件,我会得到异常:

  

该进程无法访问文件“___。xml”,因为它已被其他进程使用。

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

亲切的问候

1 个答案:

答案 0 :(得分:2)

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

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