本文介绍了序列化列表<>并将其存储在数据库中,然后获取并反序列化二进制数据并重新创建列表<>再次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些列表<>我的应用程序中的对象,我想序列化这些列表并将它们插入数据库,然后我想反序列化从数据库中提取的二进制数据,以重新生成列表<>再次
谢谢
这是序列化部分::::
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;
推荐答案
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;
}
这篇关于序列化列表<>并将其存储在数据库中,然后获取并反序列化二进制数据并重新创建列表<>再次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!