Alma Alma - 1 year ago 60
C# Question

GetBytes in C# not returning correct value

I have a method that execute stored procedure and returns values of that stored procedure. I have a VIN that in SQL is in

type. I am not sure what can I use to get the value.

This is my code:

// Get Customer Product By CustomerID
public Model.CustomerProduct Get_CustomerProduct(int Customer_ID)
Model.CustomerProduct model = null;

string myConnection = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName].ToString();
SqlDatabase db = new SqlDatabase(myConnection);
int bufferSize = 100;

byte[] outByte = new byte[bufferSize];
using (DbCommand command = db.GetStoredProcCommand("Get_Customer_Product"))
db.AddInParameter(command, "Customer_ID", DbType.Int32, Customer_ID);

var result = db.ExecuteReader(command);

if (result.FieldCount == 0)
model = null;
model = new Model.CustomerProduct()
Product_Name = result.GetString(2)
,VIN =result.GetBytes(3,0,outByte,0,bufferSize) // this return me wrong

catch (Exception ex)

return model;

My problem is this line:

VIN =result.GetBytes(3,0,outByte,0,bufferSize)

This is returning 44 however the value that is suppose to return is:


Answer Source

The GetBytes method returns the number of bytes it has written to the array, not the bytes themselves. Have a look at the contents of outByte and you should find your data there.

I would also suggest you first call GetBytes with a null buffer. This will cause it to return the length of the field, allowing you to size your buffer properly:

int len = result.GetBytes( 3, 0, null, 0, 0 );
byte[] buf = new byte[len];
result.GetBytes( 3, 0, buf, 0, buf.Length );

model = new Model.CustomerProduct()
    Product_Name = result.GetString(2),
    VIN = buf

If the code you have now runs, you most likely will have to change the type of VIN to a byte[] too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download