2011-08-24 39 views
0

我有一個流讀取器,我正在使用它來讀取流中的行。這工作得很好,但我希望能夠得到最後一行,永遠不會以換行符結束,所以readLine()將不會捕獲它。從StreamReader獲取殘餘

我將存儲這是一個全局變量,並在下一次運行之前追加到流中。

這可能嗎?

void readHandler(IAsyncResult result) 
{ 
    tcpClient = (TcpClient)result.AsyncState; 
    StreamReader reader ; 
    string line; 
    using (reader = new StreamReader(stream)) 
    { 
     while((line = reader.ReadLine()) != null){ 
      System.Diagnostics.Debug.Write(line); 
      System.Diagnostics.Debug.Write("\n\n"); 
     } 

    } 
    getData(); 
}  

回答

1

ReadLine確實捕捉,即使它沒有後一個斷行流的最後一行。例如:

using System; 
using System.IO; 

class Test 
{ 
    static void Main() 
    { 
     string text = "line1\r\nline2"; 

     using (TextReader reader = new StringReader(text)) 
     { 
      string line; 
      while((line = reader.ReadLine()) != null) 
      { 
       Console.WriteLine(line); 
      } 
     } 
    } 
} 

打印:

line1 
line2 

ReadLine()只有返回null當它到達流的末尾,返回數據的所有

+0

任何方式告訴哪一個是最後一行然後我可以提取? –

+1

@Lee:只有一個額外的局部變量...你想避免處理的方式與其餘的一樣嗎?目前還不完全清楚您需要在真實代碼中執行哪些操作。 –

+0

啊,是的,對不起,我的壞,它工作! –

0

除非您真的需要逐行執行此操作,否則您可以取消整個循環,只需使用StreamReader.ReadToEnd方法即可。這會給你當前緩衝區中的所有內容。