By   February 28, 2014
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace ConsoleApplication13
{
    public class MyClass
    {
        public int MyProperty { get; set; }

        public string MyProperty2 { get; set; }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            // create an object
            var data = new MyClass()
            {
                MyProperty = 5,
                MyProperty2 = "abc"
            };

            // create serailizer
            var serializer = new DataContractSerializer(typeof(MyClass));

            // serialization
            string path = @"C:\Temp\test.bin";
            using (var fs = File.OpenWrite(path))
            using (var writer = XmlDictionaryWriter.CreateBinaryWriter(fs))
            {
                serializer.WriteObject(writer, data);
            }

            // deserialization
            MyClass data2;
            using (var fs = File.OpenRead(path))
            using (var reader = XmlDictionaryReader.CreateBinaryReader(fs, XmlDictionaryReaderQuotas.Max))
            {
                data2 = (MyClass)serializer.ReadObject(reader);
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *