Serializing/deserializing with memory stream

前端 未结 3 1546
难免孤独
难免孤独 2020-11-30 01:27

I\'m having an issue with serializing using memory stream. Here is my code:

/// 
/// serializes the given object into memory stream
///          


        
3条回答
  •  一个人的身影
    2020-11-30 01:55

    Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize and add following two methods:

    public class SerilizeDeserialize
    {
    
        // Serialize collection of any type to a byte stream
    
        public static byte[] Serialize(T obj)
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                BinaryFormatter binSerializer = new BinaryFormatter();
                binSerializer.Serialize(memStream, obj);
                return memStream.ToArray();
            }
        }
    
        // DSerialize collection of any type to a byte stream
    
        public static T Deserialize(byte[] serializedObj)
        {
            T obj = default(T);
            using (MemoryStream memStream = new MemoryStream(serializedObj))
            {
                BinaryFormatter binSerializer = new BinaryFormatter();
                obj = (T)binSerializer.Deserialize(memStream);
            }
            return obj;
        }
    
    }
    

    How To use these method in your Class:

    ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
    Console.WriteLine("Serializing to Memory : arrayListMem");
    byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);
    
    ArrayList arrayListMemDes = new ArrayList();
    
    arrayListMemDes = SerilizeDeserialize.Deserialize(stream);
    
    Console.WriteLine("DSerializing From Memory : arrayListMemDes");
    foreach (var item in arrayListMemDes)
    {
        Console.WriteLine(item);
    }
    

提交回复
热议问题