Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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#.

thanks

like image 724
Thomas Avatar asked Jan 19 '11 08:01

Thomas


1 Answers

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<SearchFilterDetails> _list = QueryFilterDetails.ToList<SearchFilterDetails>();

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

Deserialization

  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)
        {
        }
    }
like image 83
TalentTuner Avatar answered Sep 21 '22 19:09

TalentTuner