C# Serialization Guide Part1 – xml serializer

11 בApril 2014

תגיות: , , ,
אין תגובות

How to serialize an Object ? what is the options for serializations method? And what the benefits

.using those ways

Serialization is an Process that takes an Data and parse it into a kind of file, or physical unit at

.the memory, or database

The main two popular ways are binary serialization and xml serialization

.For a small demo lets declare an Object we like to serialize

public class MyData

    {

        public int PublicID { get; set; }


        private int PrivateID;


        public string Value;


        public InternalData referenceData { get; set; }


        public void action()

        {


        }

    }

,This class contains a few kinds of Variables inc. a function for testing the serialization result

.We also have an reference type member to check the persistency of external object

:Now define some service to test the serialization options as interface

public interface ISerializeService

    {

        bool write(object data, Type type,string path);

        object read(string path,Type t);

    }

:Now lets try with xmlSerializer as following

public class XMLSerializeService :ISerializeService

    {

        public bool write(object data, Type type, string path)

        {

            bool res = false;

            XmlSerializer serializer = new XmlSerializer(type);

            try

            {

                using (StreamWriter streamWriter = System.IO.File.CreateText(path))

                {

                    serializer.Serialize(streamWriter, data);

                }

                res = true;

            }

            catch (Exception ex)

            {

                res = false;

            }

            return res;

        }


       public object read(string path, Type type)

        {

            XmlSerializer serializer = new XmlSerializer(type);

            using (TextReader reader = new StreamReader(path))

            {

                var ReaderData = serializer.Deserialize(reader);

                return (object)ReaderData;

            }


            return null;

       }


    }

Well , after running this code we can see the result of serialize service

static void Main(string[] args)

        {

            ISerializeService serializer;


            MyData dat = new MyData()

            {

                PublicID = 123, Value = "blabla",

                referenceData = new InternalData() {internalValue="test" }

            };

            serializer = new XMLSerializeService();

            serializer.write(dat, typeof(MyData), "C://data.txt");

            MyData GenertedData = (MyData)serializer.read("C://data.txt", typeof(MyData))


הוסף תגובה
facebook linkedin twitter email

Leave a Reply

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