views:

55

answers:

3

How can I save a byte[] array into a SQL Server database? This byte[] contains a HashAlgorithm value.

The data is needed again for later use. So converting it and NOT getting it back in its original state, is not what I want.

Thanks in advance!

+1  A: 

Use VARBINARY

anivas
+5  A: 

You should be able to write something like this:

string queryStmt = "INSERT INTO dbo.YourTable(Content) VALUES(@Content)";

using(SqlConnection _con = new SqlConnection(--your-connection-string-here--))
using(SqlCommand _cmd = new SqlCommand(query, _con))
{
   SqlParameter param = _cmd.Parameters.Add("@Content", SqlDbType.VarBinary);
   param.Value = YourByteArrayVariableHere;

   _con.Open();
   _cmd.ExecuteNonQuery();
   _con.Close();
}

Using Linq-to-SQL, you'd write something like this:

using(YourDataContextHere ctx = new YourDataContextHere())
{
   SomeClassOfYours item = new SomeClassOfYours();

   item.ByteContent = (your byte content here);

   ctx.SomeClassOfYourses.InsertOnSubmit(item);
   ctx.SubmitChanges();
}

That will insert your byte[] into a column Content of type VARBINARY in your SQL Server table as a byte stream, which you can read back 1:1 again later on.

marc_s
Good answer. However, based on the statement that the value is a hash, it's possible that it will be of constant length. If so, consider using binary with that length instead of varbinary.
Sean Reilly
@Sean Reilly: true - but different hash algorithms also produce different length hashes, so you might want to use a VARBINARY with a suitable max length to accomodate all variations
marc_s
@marc_s i'll be using linq. do i have to do SqlDbType.VarBinary?
Yustme
@Yustme: updated my answer to include Linq-to-SQL, too. Yes, you'll need a VARBINARY column in your SQL Server table whichever way you access it. In Linq-to-SQL, it'll show up as a "binary" column in your entity class, which you can just set (and read out) like any other column.
marc_s
@marc_s ok i'll give it a try and let you know if it worked out. thanks!
Yustme
@marc_s also true - however it's quite possible that all rows are the same hash algorithm. If (and only if) that is the case, I'd stand by my recommendation for a constant length binary instead of varbinary.
Sean Reilly
+1  A: 

Varbinary or CHAR - with the value converted to a hex. I do that pretty often with hash values because it allows me to SEE and COMPARE them easily (on rintouts, during development), and the overhead is minimal.

TomTom