尝试在 while 循环中运行 eof 语句时出现溢出异常 Value was either too large or too small for a character
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);
}
最佳答案
首先您读取文件的 1024 字节(这可能是您到达文件末尾)然后您尝试读取下一个字节,在这种情况下将返回 -1 并且不能转换为 char。
您为什么要读取第一个 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];
关于c# - 文件流溢出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46125683/