Search code examples
c#xmldocument

Issue with XmlDocument Open XML file directly after using throws exception


I have a strange issue with my XmlDocument class.

I write some XML file with it, which works great. And I have Save() method:

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);
    }
}

Like everyone sees, I'm using "using" which should give the xml free :) But if I try to read this file directly after calling Save() I get the exception:

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

Can someone explain that to me and give me a solution for it?

Kind regards


Solution

  • You are not disposing your file stream. Try changing your code like this.

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