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

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.

Leave a Comment