为什么FileStream没有被XmlReader关闭 [英] Why is FileStream not closed by XmlReader
问题描述
所以我正在 XmlReader
using (XmlReader reader = XmlReader.Create(new FileStream(archivePath, FileMode.Open), readerSettings))
{
reader.close()
}
但是,在 using
作用域之后,送入 XmlReader
的文件仍然处于锁定状态,很奇怪,我认为 XmlReader
是会为我关闭 FileStream
,不是吗?
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?
感谢您的帮助.
推荐答案
您尝试过吗?
using(var stream = new FileStream(archivePath, FileMode.Open))
using(var reader = XmlReader.Create(stream, readerSettings))
{
}
我在文档中找不到任何明确声明 XmlReader
将在基础流被处置时调用dispose的内容.另外,我总是按上面所示的方式使用它,而且从未遇到过问题.
I couldn't find anything in the documentation that explicitly stated that the XmlReader
would call dispose on the underlying stream when it was disposed. Also, I always use it as shown above and I have never encountered a problem.
浏览反射器时,我也没有发现在创建 XmlTextReaderImpl
时在流上调用 Dispose()
的任何实例. XmlTextReaderImpl
未实现 Dispose()
,其 Close()
方法如下所示:
Browsing through reflector I also find no instances where it calls Dispose()
on the stream when creating a XmlTextReaderImpl
. The XmlTextReaderImpl
does not implement Dispose()
and its Close()
method looks like this:
internal void Close(bool closeInput)
{
if (this.parsingFunction != ParsingFunction.ReaderClosed)
{
while (this.InEntity)
{
this.PopParsingState();
}
this.ps.Close(closeInput);
this.curNode = NodeData.None;
this.parsingFunction = ParsingFunction.ReaderClosed;
this.reportedEncoding = null;
this.reportedBaseUri = string.Empty;
this.readState = ReadState.Closed;
this.fullAttrCleanup = false;
this.ResetAttributes();
}
}
这篇关于为什么FileStream没有被XmlReader关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!