coffeeak
coffeeak

Reputation: 3120

Insert and retrieve ByteArray from SQL Server in C#

I have a 128-bit key that I want to store in a database. My code creates the key as byte[16] and the datatype in the database is varbinary(16).

When I try to retrieve the byte array again from the db, I don't get the original values.

Here is my code:

byte[] test =  new byte[16]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

SqlCommand myInsertCmd = new SqlCommand("INSERT INTO Test(test) VALUES(@Param)", myConnection);       
SqlParameter param = myInsertCmd.Parameters.Add("@Param", SqlDbType.VarBinary, 16);
param.Value = test;

myInsertCmd.ExecuteNonQuery();

SqlDataAdapter myAdapter1 = new SqlDataAdapter("Select test from Test;", myConnection);
DataTable dt = new DataTable();
myAdapter1.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    char[] charArray = row["test"].ToString().ToCharArray();
}

For charArray, I get 0x0053, 0x0079,0x0073,0x0074, etc and also, the charArray is only 13 bytes long. What am I doing wrong?

Upvotes: 8

Views: 26137

Answers (1)

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

row["Test"] contains byte[], so row["Test"].ToString() returns default ToString of byte[] type, which is "System.Byte[]". After which you convert System.Byte[] and get that result

foreach (DataRow row in dt.Rows)
{
    byte[] byteArray = (byte[])row["test"];
}

Upvotes: 15

Related Questions