你如何在c#中反序列化varbinary?

时间:2016-11-17 18:41:46

标签: c# asp.net serialization asp.net-core asp.net-core-mvc

我跟着this guide将会话数据存储在sql server表中。

如何解除存储的值? sql数据类型是varbinary。

我试过这个,但是我在反序列化行上遇到了这个错误:“输入流不是有效的二进制格式”

BinaryFormatter formatter = new BinaryFormatter();

byte[] byteVal = _context.Sessions.First().Value;
System.IO.Stream stream = new System.IO.MemoryStream(byteVal);
var des = formatter.Deserialize(stream);

1 个答案:

答案 0 :(得分:0)

以下代码检索您的值并将其放在名为byteVal的字节数组中:

byte[] byteVal = _context.Sessions.First().Value;

我个人更喜欢命名这样一个字节数组bytes而不是byteVal,只是为了让它更加清楚它的多个字节长。

byte[] bytes = _context.Sessions.First().Value;

无论如何,此时您可以将bytes与任何接受字节数组的方法一起使用。 (如会话存储)

因此不需要序列化或序列化。