2017-09-08 125 views
2

试图运行在while循环价值要么过大或过小的字符的EOF声明的FileStream溢出异常

string filePath = @"C:\Users\Klanix\Desktop\NewC#\testfile2.txt"; 

     FileStream fs = File.Open(filePath, FileMode.Open); 

     char readChar; 
     byte[] b = new byte[1024]; 

     while(fs.Read(b, 0, b.Length) > 0) 
     { 
      readChar = Convert.ToChar(fs.ReadByte()); 
      Console.WriteLine(readChar); 
     } 
+0

https://stackoverflow.com/questions/11985348/read-and-output-a-text-file-using-streamreader-char-by-char –

回答

1

首先你读文件的1024字节(当获取溢出异常这可能是你到达文件的末尾),那么你尝试读取下一个字节,在这种情况下,将返回-1,不能转换为字符。

你为什么要读第一个1024字节? 尝试每次读1个字节:

string filePath = @"C:\Users\Klanix\Desktop\NewC#\testfile2.txt"; 
FileStream fs = File.Open(filePath, FileMode.Open); 
int val; 
while((val = fs.ReadByte()) > 0) 
{ 
    readChar = Convert.ToChar(val); 
    Console.WriteLine(readChar); 
} 

,你会不会需要byte[] b = new byte[1024];

+0

谢谢我看到我现在犯的错误。感谢您清除我的仁慈:)。 – ThatOneCoderDude

+0

非常欢迎 –

0

要调用fs.ReadByte()没有先检查fs仍然有留下一个字节。由于您致电while(fs.Read(b, 0, b.Length) > 0),您很可能会将fs清空为b,然后致电fs.ReadByte()导致您的错误。

试着这么做:

string filePath = @"C:\Users\Klanix\Desktop\NewC#\testfile2.txt"; 

FileStream fs = File.Open(filePath, FileMode.Open); 

for (int i = 0; i < fs.Length; i++) 
{ 
    char readChar = Convert.ToChar(fs.ReadByte()); 
    Console.WriteLine(readChar); 
} 

也尝试阅读文档ReadByte