Given this table
create table dbo.bin_test
(
c1 binary(8) not null ,
c2 binary(8) null ,
c3 varbinary(8) not null ,
c4 varbinary(8) null ,
)
insert dbo.bin_test values ( 0x1234 , null , 0x1234 , null )
insert dbo.bin_test values ( 0x012345678 , 0x12345678 , 0x12345678 , 0x12345678 )
This code (IF you're going to use SQLBinary)
string connectString = "Server=localhost;Database=sandbox;Trusted_Connection=True;" ;
using ( SqlConnection connection = new SqlConnection(connectString) )
using ( SqlCommand cmd = connection.CreateCommand() )
{
cmd.CommandText = "select * from dbo.bin_test" ;
cmd.CommandType = CommandType.Text ;
connection.Open() ;
using ( SqlDataReader reader = cmd.ExecuteReader() )
{
int row = 0 ;
while ( reader.Read() )
{
for ( int col = 0 ; col < reader.FieldCount ; ++col )
{
Console.Write( "row{0,2}, col{1,2}: " , row , col ) ;
SqlBinary octets = reader.GetSqlBinary(col) ;
if ( octets.IsNull )
{
Console.WriteLine( "{null}");
}
else
{
Console.WriteLine( "length={0:##0}, {{ {1} }}" , octets.Length , string.Join( " , " , octets.Value.Select(x => string.Format("0x{0:X2}",x)))) ;
}
}
Console.WriteLine() ;
++row ;
}
}
connection.Close() ;
}
should produce:
row 0, col 0: length=8, { 0x12 , 0x34 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }
row 0, col 1: {null}
row 0, col 2: length=2, { 0x12 , 0x34 }
row 0, col 3: {null}
row 1, col 0: length=8, { 0x00 , 0x12 , 0x34 , 0x56 , 0x78 , 0x00 , 0x00 , 0x00 }
row 1, col 1: length=8, { 0x12 , 0x34 , 0x56 , 0x78 , 0x00 , 0x00 , 0x00 , 0x00 }
row 1, col 2: length=4, { 0x12 , 0x34 , 0x56 , 0x78 }
row 1, col 3: length=4, { 0x12 , 0x34 , 0x56 , 0x78 }
But as noted, it's probably cleaner to simply do this:
byte[] octets = reader[0] as byte[] ;
if ( octets == null )
{
Console.WriteLine( "{null}");
}
else
{
Console.WriteLine( "length={0:##0}, {{ {1} }}" , octets.Length , string.Join( " , " , octets.Select(x => string.Format("0x{0:X2}",x)))) ;
}
And get the same result.