Serialize Object to byte array - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Serialize Object to byte array

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Linq;
using System.IO.Compression;
using System.IO;//from  w w  w .  j  av a 2 s.  c o  m
using System.Collections.Generic;
using System;

public class Main{
        public static byte[] SerializeObject(object obj)
        {
            if (obj == null)
                return null;
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, bytes.Length);
            ms.Close();
            return bytes;
        }
}

Related Tutorials