I have a BLOB from an Oracle database. In .NET it is of type OracleLob and has among them a Read and ReadByte methods.
int OracleLob.Read(byte[] buffer, int offset, int count)
int OracleLob.ReadByte()
So the Read method reads a sequence of bytes and ReadByte reads a single byte at a time. Here is my code:
OracleLob ol = (OracleLob) cmd.Parameters[1].Value; //her er filen!!
BinaryWriter binWriter = new BinaryWriter(File.Open(@"D:\wordfile.DOCX", FileMode.Create));
int currentByte = ol.ReadByte();
while (currentByte != -1)
{
binWriter.Write(currentByte);
currentByte = ol.ReadByte();
}
binWriter.Close();
But when I open wordfile.DOCX in Word, it says that the file is corrupt and cannot be opened. What am I doing wrong?
What’s wrong with the code is that it’s using an
intvalue when writing the byte data to theBinaryWriter. It’s using the overload that is writing anintinstead of the one writing abyte, so each byte from the source will be written as four bytes. If you check the file size you see that it’s four times as large as it should be.Cast the value to
byteso that the correct overload of theWritemethod is used:To do this more efficiently, you can use a buffer to read blocks of bytes instead of a single byte at a time: