how to serialize class to database instead of file system c#

后端 未结 6 2249
南笙
南笙 2021-02-10 19:10

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 c

6条回答
  •  孤街浪徒
    2021-02-10 19:40

    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

    Serialization

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

    Deserialization

      private void DeSerilizeQueryFilters(byte[] items)
        {
            BinaryFormatter bf = new BinaryFormatter();
    
            List _list = new List();
    
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(items, 0, items.Length);
                    ms.Position = 0;
    
                    _list = bf.Deserialize(ms) as List;
                }
    
                foreach (SearchFilterDetails mobj in _list)
                {
                    QueryFilterDetails.Add(mobj);
                }
            }
            catch (Exception ex)
            {
            }
        }
    

提交回复
热议问题