Wednesday 30 March 2016

c# serialization

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication2
{
    [Serializable()]
    public class worker
    {
        public string person;
        public long phone;
    }

    [Serializable()]
    public class database
    {
        public SortedList<int, worker> db = new SortedList<int, worker>();
        public void save()
        {
            FileStream f = new FileStream(@"d:\people.dat",
                FileMode.Create);
            BinaryFormatter b = new BinaryFormatter();
            b.Serialize(f, this);
            f.Close();
        }
        public database load()
        {
            BinaryFormatter b = new BinaryFormatter();
            using (FileStream f = new FileStream(@"d:\people.dat",
                                    FileMode.Open))
            {
                return (database)b.Deserialize(f);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            database d = new database();

            worker w = new worker();
            w.person = "abc";
            w.phone = 123;
            d.db[1] = w;

            worker w1 = new worker();
            w1.person = "bcd";
            w1.phone = 234;
            d.db[2] = w1;

            d.save();

            d = d.load();

            Console.WriteLine(d.db[1].person + "  " + d.db[1].phone);
            Console.WriteLine(d.db[2].person + "  " + d.db[2].phone);

            Console.ReadLine();
        }
    }
}

-----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization; //allows classes to be saved/copied
using System.Runtime.Serialization.Formatters.Binary;

namespace file5demo
{
    [Serializable()] //vb <Serializable()> _
    class emp
    {   public string name;
        public double rate;
    }
    //ways to copy a class
    //1. copy each variable
    //2. make a Copy method
    //3. make a Clone method
    //4. use serializing to copy everything in a class
    class Program
    {   static void Main(string[] args)
        {   emp x = new emp();
            emp y = new emp();
            x.name = "bob";
            x.rate = 15.00;
            //code to copy a class
            MemoryStream m = new MemoryStream();
            BinaryFormatter b = new BinaryFormatter();
            b.Serialize(m, x);
            m.Seek(0, 0); //reset memory to beginning
            y = (emp)b.Deserialize(m);
            //confirm
            Console.WriteLine(y.name);
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment