2013-08-05 70 views
-4

您好,我想一次只讀取文件中的兩個字符一次讀取文件2個字符

任何機構都可以幫助我如何做到這一點?

下一次當我閱讀時,我必須讀取下兩個字符,依此類推,直到文件結束。

請幫助

+0

你有沒有嘗試什麼嗎? –

+0

http://msdn.microsoft.com/en-us/library/vstudio/94223t4d.aspx –

+1

爲什麼不把整個文件內容讀入一個字符串,然後對字符串進行操作(從字符串中獲取2個字符),因此,您將減少I/O操作的數量並且它會更快 – testuser

回答

1

您應該能夠使用StreamReader.ReadBlock方法來做到這一點。

將該方法傳遞給一個雙字符長度的數組,告訴它開始在索引0處寫入並讀取兩個字符。

1

嘗試使用StreamReader或結合一個StringReader與任何其他Stream,這裏我用FileStreamStreamReader

int currentPosition = 0L; 

using (var fs = new FileStream(filePath, FileMode.Open)) 
{ 
    using (var sr = new StreamReader(fs)) 
    { 
     char[] buffer = new char[2]; 

     sr.Read(buffer, currentPosition, 2); 

     // buffer now contains the first 2 characters in the file, use a loop or similar to read the rest of the file 
    } 
} 
相關問題