Why is FileStream not closed by XmlReader

TOMMY WANG picture TOMMY WANG · Mar 23, 2012 · Viewed 10k times · Source

So I am using the FileStream inside XmlReader

using (XmlReader reader = XmlReader.Create(new FileStream(archivePath, FileMode.Open), readerSettings))
{
    reader.close()
}

However, the file feed into the XmlReader is still in the lock state after the using scope, weird, I thought the XmlReader is going to close the FileStream for me, is it not?

Thanks for help.

Answer

Eric Patrick picture Eric Patrick · Nov 30, 2012

You should be able to control this through XmlReaderSettings.CloseInput.

readerSettings.CloseInput = true;
using (XmlReader reader = XmlReader.Create(new FileStream(archivePath, FileMode.Open), readerSettings))
{
    // do work with the reader
}

Or, more concisely if you don't care about other reader settings:

using (XmlReader reader = XmlReader.Create(new FileStream(archivePath, FileMode.Open), new XmlReaderSettings() { CloseInput = true }))
{
    // do work with the reader
}