Search code examples
c#overflowexception

FileStream Overflow Exception


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

Solution

  • 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];