C# – datatable not accepting the value of varbinary

asp.netcdatabasedatatablesql server

the value buf has a datatype varbinary(max) and the value is 0x0000002D

string buF =
    "0x" + BitConverter.ToString((byte[])dt.Rows[i]["BuF"]).Replace("-", "");
    Label3.Text = buF;

i use the value to find the fileid

DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = ConfigurationManager.ConnectionStrings["XYZ"].ConnectionString;
        connection.Open();
        SqlCommand sqlCmd = new SqlCommand("SELECT FileID FROM Backed where MachineID = @machineID  AND BuF =@buF", connection);
        SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
        sqlCmd.Parameters.AddWithValue("machineID", strID);
        sqlCmd.Parameters.AddWithValue("buF", buF);
        sqlDa.Fill(dt);
        connection.Close();

i does not use the value of buf and i dont get the correct filid….

but if i use this with the value0x0000002D instead of buf i get the file id… why is this happening… i tried everything but nothing seems to work

i need help

Best Answer

The equivalent type for varbinary in C# is byte[], not string. Also, as Hogan said, AddWithValue tries to assume a data type. Instead, you can make it explicit:

sqlCmd.Parameters.Add("buF", SqlDbType.VarBinary, -1).Value = yourByteArray;

The -1 for length corresponds to varbinary(max).