Using MemoryStream to Serialize and Desirialize : Memory Stream « File Stream « C# / C Sharp






Using MemoryStream to Serialize and Desirialize

 
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace PDM.Data
{
    public class SerializerUtil
    {
        private static readonly XmlSerializer _serializer = new XmlSerializer(typeof(List<object>));

        public static string SerializeList(List<object> list)
        {
            using (var stream = new MemoryStream())
            {
                _serializer.Serialize(stream, list);
                stream.Position = 0;
                return Encoding.UTF8.GetString(stream.GetBuffer());
            }
        }

        public static List<object> DesirializeList(string data)
        {
            if (string.IsNullOrEmpty(data))
                return null;

            using (var stream = new MemoryStream())
            {
                var bytes = Encoding.UTF8.GetBytes(data);
                stream.Write(bytes, 0, bytes.Length);
                stream.Position = 0;
                return (List<object>)_serializer.Deserialize(stream);
            }
        }
    }
}

   
  








Related examples in the same category

1.Create a MemoryStream
2.MemoryStream.Write
3.Use MemoryStream and BinaryWriter to convert decimal to byte arrayUse MemoryStream and BinaryWriter to convert decimal to byte array
4.Use MemoryStream and BinaryReader to convert Byte array to decimalUse MemoryStream and BinaryReader to convert Byte array to decimal
5.MemoryStream.ToArray, MemoryStream.ReadDecimal
6.Deep Copy with MemoryStream
7.Memory-Mapped Files
8.Deep clone with MemoryStream
9.Convert a string into an array of bytes