FileStream Overflow Exception

435 Views Asked by At

Get an overflow exception when trying to run an eof statement in the while loop 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);
        }
2

There are 2 best solutions below

1
Ashkan Mobayen Khiabani On BEST ANSWER

First you read 1024 byte of the file (that may be you reach the end of file) then you try to read the next byte that in this case would return -1 and can not be converted to char.

Why would you even read that first 1024 byte? Try reading 1 byte each time:

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);
}

and you won't need byte[] b = new byte[1024];

0
Trisped On

You are calling fs.ReadByte() without first checking that fs still has a byte left. Because you are calling while(fs.Read(b, 0, b.Length) > 0) you will most likely empty fs into b, then call fs.ReadByte() resulting in your error.

Try something like:

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);
}

Try also reading the documentation for ReadByte.