Search code examples
type-conversionintbytefilestream

Convert FileStream.ReadByte() returned int to byte?


I need to read all raw bytes in a file and then send them in a byte stream. My problem is that FileStream.ReadByte() returns an int. I can't convert it to a byte. For example:

FileStream fStream = new FileStream(filePath);
byte readByte = Convert.ToByte(fStream.ReadByte()); // Throws converted value too large for unsigned byte exception!
byteBuffer[index] = readByte; // Need the raw byte for this byte buffer.

How do I solve this in C#?

Thanks and have a nice weekend!


Solution

  • ReadByte returns byte, cast to an Int32, or -1 if the end of the stream has been reached. You get the exception at the end of file when -1 is returned which can't be converted to byte. So just check for it, for example

    var tmp = fStream.ReadByte();
    if (tmp == -1)
        // end of file reading
    else 
        byteBuffer[index] = Convert.ToByte(tmp);