如何序列化类数据库,而不是文件系统C# [英] how to serialize class to database instead of file system c#

查看:119
本文介绍了如何序列化类数据库,而不是文件系统C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以很容易地序列化类平面文件,但如果我想序列类数据库的话,我怎么能做到这一点,如果可能的话那我怎么才能从数据库到类反序列化的数据。
请给C#中的示例代码。

we can easily serialize class to flat file but if i want to serialize class to database then how could i do it and if it is possible then how can i deserialize data from db to class. please give a sample code in c#.

感谢

推荐答案

像对方说的已经,您可以使用二进制序列化,以获得byte []数组的内存流,然后在BLOB类型的数据库中创建一个列/图像存储字节数组。

Like other said at already, you can use binary serialization to get the Byte[] array in a memory stream and then create a column in database of type Blob / image to store the the byte array.

然后一边读回来了,你刚刚复出利用所谓的反序列化的技术。

Then while reading back, you just read the value of the column in the stream back by using technique called deserialization

序列读取流中的列的值

  BinaryFormatter bf = new BinaryFormatter();

        List<SearchFilterDetails> _list = QueryFilterDetails.ToList<SearchFilterDetails>();

        using (MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, _list);
            return ms.GetBuffer();
        }



反序列化

  private void DeSerilizeQueryFilters(byte[] items)
    {
        BinaryFormatter bf = new BinaryFormatter();

        List<SearchFilterDetails> _list = new List<SearchFilterDetails>();

        try
        {
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(items, 0, items.Length);
                ms.Position = 0;

                _list = bf.Deserialize(ms) as List<SearchFilterDetails>;
            }

            foreach (SearchFilterDetails mobj in _list)
            {
                QueryFilterDetails.Add(mobj);
            }
        }
        catch (Exception ex)
        {
        }
    }

这篇关于如何序列化类数据库,而不是文件系统C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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