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!
In Sql Server, use image data type or varbinary data type, to store byte array data.
varbinary(max) which is used to store large binary values (BLOBs) up to 2GB. The actual value is stored in a separate location if it's larger than 8000 bytes and just a pointer is stored in the row itself. This type is available since SQL Server 2005. image data type was used to store BLOBs prior to SQL Server 2005.
Byte is an immutable value type that represents unsigned integers with values that range from 0 to 255. You can almost convert any kind of data into Byte Array(Byte []) like File, Image, Xml and etc.. In SQL Server, we have enough datatypes to store string text, int, bool, datatime and even Xml.
On the File tab, click Save As. Do one of the following steps: To save a database in a different format, click Save Database As. To save a database object in a different format, click Save Object As.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With