2

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+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 - 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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.