问题描述
我有一个方法,它可以是一个 StringReader
实例(从剪贴板读取)或者的StreamReader
实例(从文件中读取),并在present,铸就一方为的TextReader
实例。
I have a method that takes either a StringReader
instance (reading from the clipboard) or a StreamReader
instance (reading from a file) and, at present, casts either one as a TextReader
instance.
我需要它'pre-读的一些源输入,然后重置光标回到开始。我不一定有原来的文件名。怎么我做到这一点?
I need it to 'pre-read' some of the source input, then reset the cursor back to the start. I do not necessarily have the original filename. How to I do this?
有提到寻找
的System.IO.Stream
的方法,但这不是在执行<$的C $ C>的TextReader ,虽然它在的StreamReader
通过 Basestream
属性。然而 StringReader
不具有 BaseStream
属性
There is mention of the Seek
method of System.IO.Stream
but this is not implemented in TextReader
, although it is in StreamReader
through the Basestream
property. However StringReader
does not have a BaseStream
property
推荐答案
这取决于的TextReader
。如果它是一个的StreamReader
,你可以使用:
It depends on the TextReader
. If it's a StreamReader
, you can use:
sr.BaseStream.Position = 0;
sr.DiscardBufferedData();
(假设底层流当然是可查找,。)
(Assuming the underlying stream is seekable, of course.)
的其他实现的TextReader
不可以有无的的倒带的一个概念,在同样的方式,的IEnumerable&LT; T&GT;
没有。在许多方面,你能想到的的TextReader
作为一个荣耀的的IEnumerable&LT;焦炭&GT;
。它的方法来读取数据的整个块的时间,读线等,但它本质上是一个向前读型。
Other implementations of TextReader
may not have a concept of "rewinding", in the same way that IEnumerable<T>
doesn't. In many ways you can think of TextReader
as a glorified IEnumerable<char>
. It has methods to read whole chunks of data at a time, read lines etc, but it's fundamentally a "forward reading" type.
编辑:我不相信 StringReader
支持任何种类的收卷 - 你会更好重现 StringReader
从原来的字符串,如果你能。如果这不可行,你总是可以创建自己的的TextReader
类,它代理了所有的正常呼叫转接至其他 StringReader
,但重新创建该代理实例时,它需要。
I don't believe StringReader
supports any sort of rewinding - you'd be better off recreating the StringReader
from the original string, if you can. If that's not feasible, you could always create your own TextReader
class which proxies all the "normal" calls to another StringReader
, but recreates that proxy instance when it needs to.
这篇关于你如何重置一个C#.NET的TextReader光标回到起点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!