Thursday, 24 May 2018

Serialization and Deserialization in C#





C# Serialization

string path = @"C:\Users\salman\Desktop\FILE\serial.doc";

         

            Student s = new Student(1, "Salman");

            FileStream stream = new FileStream(path, FileMode.OpenOrCreate);

            BinaryFormatter formater = new BinaryFormatter();

            formater.Serialize(stream, s);

            stream.Close();

            Console.ForegroundColor = System.ConsoleColor.Red;

            Console.WriteLine("File saved in "+path);

            Console.ReadLine();



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

C# Deserialization





string path = @"C:\Users\salman\Desktop\FILE\serial.doc";

 FileStream stream = new FileStream(path, FileMode.OpenOrCreate);

            BinaryFormatter formater = new BinaryFormatter();

            Student s = (Student)formater.Deserialize(stream);

            Console.ForegroundColor = System.ConsoleColor.Green;

            Console.WriteLine("Id :"+s.id);

            Console.WriteLine("Name :" + s.name);

            Console.ReadLine();
--------------------------------------------------------------

STUDENT CLASS:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication28
{   [Serializable]
    class Student
    {
        public int id;
        public string name;

        public Student(int id, string name)
        {
            this.id = id;
            this.name = name;

        }

    }
}

No comments:

Post a Comment

Pass Dynamically Added Html Table Records List To Controller In Asp.net MVC

Controller Code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ...