重置 StreamReader 以进行多个 XmlReader.Read() 用法
我想重新使用与 XML 文件关联的 StreamReader,用于来自 System.Xml.XmlReader 的 .Read() 调用。
基本上,我整理了一个具有以下代码的小型扩展方法:
public static string GetValueByPath(this StreamReader str, string attributeName, params string[] nodes)
{
str.BaseStream.Position = 0;
XmlReader reader = XmlReader.Create(str);
// Stuff happens here now, not important for the question
}
调用此扩展方法的 StreamReader 在整个会话中保持不变。
第一次时效果很好,但如果我第二次使用此方法,我会收到 System.Xml-Exception。有没有办法有效地“重置”StreamReader?
谢谢,
丹尼斯
I'd like to re-use a StreamReader I've associated with an XML file for .Read()-Calls from System.Xml.XmlReader.
Basically I've put together a small extension method featuring the following code:
public static string GetValueByPath(this StreamReader str, string attributeName, params string[] nodes)
{
str.BaseStream.Position = 0;
XmlReader reader = XmlReader.Create(str);
// Stuff happens here now, not important for the question
}
The StreamReader calling this extension method stays the same throughout the whole Session.
The first time this works just fine, but if I use this method a second time I receive a System.Xml-Exception. Is there no way to effectively "reset" a StreamReader?
Thanks,
Dennis
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能只更改
BaseStream
中的位置,因为StreamReader
正在缓冲来自底层流的数据。它只会扰乱 StreamReader 的行为,不会产生任何好处。您应该丢弃旧的 StreamReader 并每次创建一个新的。
You can't just change the position in the
BaseStream
, because theStreamReader
is buffering the data from the underlying stream. It will just mess with the behavior of theStreamReader
, nothing good will come out of it.You should dispose the old
StreamReader
and create a new one every time instead.StreamReader 的创建成本并不高,因此只要底层流支持设置位置,那么您每次都应该在其上创建一个新的 StreamReader。
StreamReader
is not an expensive object to create, so as long as the underlying stream supports setting the position then you should just create a newStreamReader
on it each time.由于它是缓冲的,因此除了重置位置之外,还需要丢弃缓冲区。
当我想知道我要解析的文件中有多少行时,我就这样做了(第一遍计算行数,第二遍解析并存储结果)。
Since it's buffering, you need to discard the buffer in addition to resetting the position.
I've done this when I want to know how many lines are in the file I'm about to parse (1st pass counts lines, 2nd pass parses and stores results).
您是否尝试过将其添加到方法的末尾?
您的阅读器可能无法正确关闭,这会导致下次阅读出现问题。
Have you tried adding this to then end of your method?
Your reader might not be closing correctly which is causing issues with the next read.