Yustme
Yustme

Reputation: 6255

Save byte[] into a SQL Server database from C#

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.

Upvotes: 51

Views: 107659

Answers (4)

Felipe de Macêdo
Felipe de Macêdo

Reputation: 344

Using Dapper you may save HTML Code easily like this:

using (var con = DapperConnection.Con)
{
    string firstValue = "any text...";
    string secondValue = "HTML code maybe ?";

    // Convert your string into byte array:
    byte[] htmlCode = Encoding.ASCII.GetBytes(secondValue);

    // Define your insert query and execute it:
    con.Execute($@" INSERT INTO [dbo].[YourTableName]
                    ( [firstColumnName], [secondColumnName] )
                    VALUES
                    ( {firstValue}, COMPRESS(@HTML) )", new { HTML = htmlCode });
}

You may then DECOMPRESS it from database like this:

SELECT [firstColumnName], CONVERT(varchar(MAX), DECOMPRESS([secondColumnName])) FROM [YourTableName];

Upvotes: 3

marc_s
marc_s

Reputation: 754468

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(queryStmt, _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.

Upvotes: 75

TomTom
TomTom

Reputation: 62093

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.

Upvotes: 2

anivas
anivas

Reputation: 6547

Use VARBINARY

Upvotes: 8

Related Questions