Use BINARY or VARBINARY to store binary data.
string query = "INSERT INTO dbo.MyTable(Content) VALUES(@Content)";
using(SqlConnection connection = new SqlConnection(/*yout connection string here*/))
using(SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
SqlParameter param = command.Parameters.Add("@Content", SqlDbType.VarBinary);
param.Value = YourByteArrayVariableHere;
command.ExecuteNonQuery();
}
You could retrieve it by using a SqlDataReader to get data and than cast the result as byte array. This code gets only the first row. If you want to get more use while (d.Read())
instead of the if (d.Read())
.
string query = "Select Content from dbo.MyTable";
using(SqlConnection connection = new SqlConnection(/*your connection string here*/))
using(SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
using (SqlDataReader d = command.ExecuteReader())
{
if (d.Read())
{
byte[] byteArray = (byte[])d["Content"];
}
}
}
4
solved c# put a byte[] into an database and retrive later [closed]