Search code examples
c#sqlvarbinary

Getting a sql varbinary record using microsoft enterprise library


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.


Solution

  • 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.