2011-08-13 51 views
4

對於C#項目,我正在使用streamreader,我需要返回1個字符(基本上像撤消),我需要它來改變,所以當你得到下一個字符時,它是與你回滾C#回滾Streamreader 1個字符

例如

你好

我們做

^h

Ë

大號

大號

ö

[空白]

Ť

ħ

Ë

ř< - 我們的未這樣做將R

所以..

[R < - 解開

[R

Ë

這是一個粗略的想法

+0

我認爲這是不可能的,因爲當你讀一個流時,它返回並前進,並且已經消失。也許可以使用文件和內存流,但考慮網絡流。你讀取數據,它是傳入的,它被處理並永遠消失,它不會被「存儲」在某個地方。但如果你特別想要這樣做,例如,內存流,你可能會去不安全的代碼,並做一些指針算術,我*認爲*它應該工作.. –

回答

-3

減去一個從位置:

var bytes = Encoding.ASCII.GetBytes("String"); 
Stream stream = new MemoryStream(bytes); 
Console.WriteLine((char)stream.ReadByte()); //S 
Console.WriteLine((char)stream.ReadByte()); //t 
stream.Position -= 1; 
Console.WriteLine((char)stream.ReadByte()); //t 
Console.WriteLine((char)stream.ReadByte()); //r 
Console.WriteLine((char)stream.ReadByte()); //i 
Console.WriteLine((char)stream.ReadByte()); //n 
Console.WriteLine((char)stream.ReadByte()); //g 
+0

對於StreamReader,訪問其BaseStream屬性並設置其位置。 –

+0

謝謝,這將工作 – Steven

+0

並非所有的流都具有CanSeek()== true。 –

2

如果您不知道是否需要該值,而不是Read(),請使用Peek() - 那麼您可以檢查值而不用推進流。另一種方法(我在我的一些代碼中使用)是在封裝閱讀器(或在我的情況下,Stream)在一個類,它有一個內部緩衝區,可以讓你推回值。緩衝區總是被首先使用,使得將值(甚至是調整後的值)推回到流中變得容易,而不必倒回(這對多個流不起作用)。

1

乾淨的解決方案是從StreamReader派生類並重寫Read()函數。

根據您的要求,簡單的private int lastChar就足以實現Pushback()方法。更通用的解決方案將使用Stack<char>來允許無限制的回傳。

//untested, incomplete 
class MyReader : StreamReader 
{ 
    public MyReader(Stream strm) 
     : base(strm) 
    { 
    } 

    private int lastChar = -1; 
    public override int Read() 
    { 
     int ch; 

     if (lastChar >= 0) 
     { 
      ch = lastChar; 
      lastChar = -1; 
     } 
     else 
     { 
      ch = base.Read(); // could be -1 
     } 
     return ch; 
    } 

    public void PushBack(char ch) // char, don't allow Pushback(-1) 
    { 
     if (lastChar >= 0) 
      throw new InvalidOperation("PushBack of more than 1 char"); 

     lastChar = ch; 
    } 
}