tags:

views:

16

answers:

1

I have this line of code

byte[] field1 = (reader.GetSqlBinary(reader.GetOrdinal("Field1")).Value;

which is a SqlDataReader

I am trying to convert the code to use the enterprise library data access block but cant figure out how to get a byte[] using the IDataReader.

I've had a good look through the MS docs but failed to find anything that helped.

+1  A: 

The first thing I would try is (where i is reader.GetOrdinal("Field1")):

    byte[] firstTry = (byte[])reader.GetValue(i);

If that fails, perhaps:

byte[] secondTry;
using (var ms = new MemoryStream())
{
    byte[] buffer = new byte[8040]; // sql page size
    int read;
    long offset = 0;
    while ((read = (int)reader.GetBytes(i, offset, buffer, 0, buffer.Length)) > 0)
    {
        ms.Write(buffer, 0, read);
        offset += read; // oops! added this later... kinda important
    }
    secondTry = ms.ToArray();
}

Note also that the behaviour may change slightly depending on whether CommandBehavior.SequentialAccess is specified.

Marc Gravell
+1 thanks Mark. "First thing" worked a treat. Looking at it I can't believe i didnt do that. The Carling is obviously taking effect. Time to close visual studio and play with spotify!
Matt Joslin
@Matt - I'm glad the first one worked - I'd missed a *crucial* step from the second ;p Now fixed, for the benefit of the "long tail".
Marc Gravell