2013-08-05 55 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 
    } 
} 
相关问题