序列化列表<>并将其存储在数据库中,然后获取并反序列化二进制数据并重新创建列表<>再次 [英] serialize a list<> and store it in the database, then fetch and deserialize the binary data and remake the list<> again

查看:121
本文介绍了序列化列表<>并将其存储在数据库中,然后获取并反序列化二进制数据并重新创建列表<>再次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些列表<>我的应用程序中的对象,我想序列化这些列表并将它们插入数据库,然后我想反序列化从数据库中提取的二进制数据,以重新生成列表<>再次





谢谢



这是序列化部分::::

i have some list<> objects in my application and i want to serialize these lists and insert them to the database , then i want to Deserialize the binary data fetched from the database to remake the list<> again


thanks

this is serialization part ::::

MemoryStream departmanStream = new MemoryStream();
// Updated with two lines from comment reply
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(departmanStream, Departments);
departmanStream.Position = 0;
byte[] DB = departmanStream.ToArray();





这里我们看到反序列化部分中的错误:::::







here we see the error in Deserialize part :::::


connection load = new connection("term_selectbyname", "name", TermToLoad);  

// get the binary codes from Database , connection is a class to connect
// to db through name of the query and the params
DataTable dt_load = new DataTable();
dt_load = load.senddt();  // send datatable from connection class and put it in the load dt
BinaryFormatter formatter = new BinaryFormatter();

string temp = dt_load.Rows[0][1].ToString();                                            
Stream departmanStream = GenerateStreamFromString(temp);
departmanStream.Position = 0;  
// Exception "End of Stream encountered before parsing was completed" occurs here.             
List<departman> dep = (List<departman>)formatter.Deserialize(departmanStream);  
grddepartman.DataSource = dep;









the上面使用的函数GenerateStreamFromString(string s)::::







the function GenerateStreamFromString(string s) used above::::

MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;

推荐答案

转换 varbinary 列到字符串,然后将字符串转换回一系列字节,最终会破坏数据。



尝试直接读取字节:

By converting a varbinary column to a string, and then converting the string back to a series of bytes, you will end up corrupting the data.

Try reading the bytes directly:
byte[] serializedData = (byte[])dt_load.Rows[0][1];
using (MemoryStream departmanStream = new MemoryStream(serializedData))
{
    List<departman> dep = (List<departman>)formatter.Deserialize(departmanStream); 
    grddepartman.DataSource = dep;
}


这篇关于序列化列表&lt;&gt;并将其存储在数据库中,然后获取并反序列化二进制数据并重新创建列表&lt;&gt;再次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆