MySqlDataReader GetBytes buffer issue...

4.5k views Asked by At

I've found a curious quirk of the MySqlDataReader.GetBytes implementation and just wondering if this is well known as I can't seem to find any articles about it on the net.

If you follow the code example for the SqlDataReader and apply it to the MySqlDataReader it wont work...unless the number of bytes in the record you are retreiving is exactly divisible by the buffer. So for example if you are on the last iteration of the loop and there is only 100 bytes left but it's trying to read another 1024 bytes then the MySqlDataReader will fail and throw an exception. The SqlDataReader will not.

Unless I'm doing something wrong?

D.

1

There are 1 answers

5
Jon Skeet On BEST ANSWER

Rather than reading the whole buffer size, only ask for at most the buffer size, but also at most what you believe is left. To be honest, you might as well create a buffer of exactly the right size rather than a fixed size one anyway.

// I assume this works for MySqlDataReader too...
int length = (int)reader.GetBytes(column, 0, null, 0, 0);
byte[] buffer = new byte[length];
int index = 0;

while (index < length)
{
    int bytesRead = (int)reader.GetBytes(column, index,
                                    buffer, index, length - index);
    index += bytesRead;
}

But if you wanted a smaller buffer (e.g. if you were processing it a buffer at a time) you could use:

int length = (int)reader.GetBytes(column, 0, null, 0, 0);
byte[] buffer = new byte[length];
int index = 0;

while (index < length)
{
    int bytesRead = (int)reader.GetBytes(column, index, buffer, 0, 
                                    Math.Max(buffer.Length, length - index));
    // Process the buffer, up to value bytesRead
    // ...
    index += bytesRead;
}