C# 文件流溢出异常
尝试在while循环中运行eof语句时,获取溢出异常值对于字符来说太大或太小C# 文件流溢出异常,c#,overflowexception,C#,Overflowexception,尝试在while循环中运行eof语句时,获取溢出异常值对于字符来说太大或太小 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,
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,并且无法转换为字符 你为什么还要读第一个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=新字节[1024]
您正在调用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);
}
string filePath=@“C:\Users\Klanix\Desktop\NewC\testfile2.txt”;
FileStream fs=File.Open(filePath,FileMode.Open);
for(int i=0;i
请尝试阅读的文档。谢谢,我现在看到了我犯的错误。谢谢你帮我澄清我的善意:)。