Gih*_*han 6 c# sql sql-server bytearray multidimensional-array
我想将多维字节数组保存到SQL Server数据库.
我知道如何保存一个字节数组,这是一个图像转换到数据库.为此,我使用的数据类型是image
.但现在我想存储另一个字节数组,它是多维字节数组byte [,] temp
,它有两个维度,带有x,y值.
我在互联网上搜索,据说使用VARBINARY
格式.我想知道的是,如果我将多维数组保存在VARBINARY
数据类型数据列中,那么值是否会被更改?是否有可能再次以多维数组的形式接收数据?
是的,您将能够不加改变地恢复您的多维阵列.
你怎么能这样做?在Sql Server中使用Varbinary(max)字段并将序列化的多维字节数组保存到其中.为了恢复你的阵列,你需要反序列化你在数据库中存储的内容.
以下是如何执行此操作的示例:
public void TestSO()
{
using (SqlConnection conexion = new SqlConnection())
{
using (SqlCommand command = new SqlCommand())
{
//This is the original multidimensional byte array
byte[,] byteArray = new byte[2, 2] {{1, 0}, {0,1}};
ConnectionStringSettings conString = ConfigurationManager.ConnectionStrings["ConnectionString"];
conexion.ConnectionString = conString.ConnectionString;
conexion.Open();
command.Connection = conexion;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE Table SET VarBinaryField = @Content WHERE Id = 73 ";
command.Parameters.Add(new SqlParameter("@Content", SqlDbType.VarBinary, -1));
//Serialize the multidimensional byte array to a byte[]
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, byteArray);
//Set the serialized original array as the parameter value for the query
command.Parameters["@Content"].Value = ms.ToArray();
if (command.ExecuteNonQuery() > 0)
{
//This method returns the VarBinaryField from the database (what we just saved)
byte[] content = GetAttachmentContentsById(73);
//Deserialize Content to a multidimensional array
MemoryStream ms2 = new MemoryStream(content);
byte[,] fetchedByteArray = (byte[,])bf.Deserialize(ms2);
//At this point, fetchedByteArray is exactly the same as the original byte array
}
}
}
}
Run Code Online (Sandbox Code Playgroud)