C# Serialization Guide Part 4 – Binary serializer

18 בApril 2014

אין תגובות

..Now, back to the basics, or may we say to the computing Origin

,Of course the base of all stream , networking , and of course a Serialization is Binary

.And to Translate an object to the smallest units of bytes

If we would try to compare Binary to XML it probably faster to process , so if we talking about

.large amount of data just think about binary

.The binary encoding is quite unreadable, but don’t trust it as encrypted

.Note: The XML could be found very useful to transfer via Web-Services for other platforms

:So again define the DTO , the Contract and the implementation

.Just noticed to the serializable attribute

[Serializable]

    public class BinarySerializeTest

    {

            private string prv = "abc";

            public string pbl = "def";

    }

public interface ISerializeService

    {

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

        object read(string path, Type t);

    }


public class BinarySerializeService : ISerializeService

    {

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

        {

            FileStream stream = File.Create(path);

            try

            {

                BinaryFormatter format = new BinaryFormatter();

                format.Serialize(stream, data);

                return true;

            }

            catch (Exception)

            {

                return false;

            }


            finally

            {

                stream.Close();

            }


        }


        public object read(string path, Type t)

        {

            object restoredObj;

            FileStream stream = File.OpenRead(path);


            try

            {

                BinaryFormatter format = new BinaryFormatter();

                restoredObj = (object)format.Deserialize(stream);

            }

            catch (Exception)

            {

                restoredObj = null;

            }

            finally

            {

                stream.Close();

            }

            return restoredObj;


        }

    }

:now all what has left is just run the test to read and write

ISerializeService serializer;


         serializer = new BinarySerializeService();

         serializer.write(new BinarySerializeTest(), null, "c://data4.txt");


    BinarySerializeTest GenertedData =

             (BinarySerializeTest)serializer.read("c://data4.txt", null);


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

Leave a Reply

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