+92 332 4229 857 99ProjectIdeas@Gmail.com

How to write a object in file (Serialization) (C#.net)


How to write a object in file (Serialization):
Serialization, as implemented in the System.Runtime.Serialization namespace is the process of serializing and deserializing objects so that they can be stored or transferred and then later re-created.
Serializing is the process of converting an object into a linear sequence of bytes that can be stored or transferred.


Code

using System.Collections.Generic;

using System.Runtime.Serialization.Formatters.Binary; // namespace to use Serialization

For Serializing a pariticular class see the below, write in above of class [Serializable]. If you dont want a Serialize the particular property of class, let say you don't want to serialize the "name" then you can write above to name

[NonSerialized]
private string name; like this.

In this particular example we are creating Employee class as Serialized. Class contains properties id and name, their getters/setters, default and parametrized constructor and one print() function.

[Serializable]
public class Employee
{
    private int id;

    public int Id
    {
        get { return id; }
        set { id = value; }
    }

    private string name;

    public string Name
    {
       get { return name; }
       set { name = value; }
    }

    // Default Constructor
    public Employee()
    {
        this.id = 0;
        this.name = "Anonymous";
    }

   // Parameterized Constructor
    public Employee(int i, string n)
    {
        this.id = i;
        this.name = n;
    }

    public void print()
    {
        Console.WriteLine("ID is : " + this.id +
                          "Name is : " + this.name);
    }
}

public static void Main(string[] args)
{
  In the main function, first we have to create the objects of Employee class:
  Three objects are created, emp , emp2 and emp3.
       Employee emp = new Employee(12, "Rehan Ali");
       Employee emp2 = new Employee(13, "Haider Shah");
       Employee emp3 = new Employee(14, "Faiz Rehman");

 Now, we have to save these objects in file, so open a file:
  FileStream fs = new FileStream("abc.dat", FileMode.Create, FileAccess.Write);

Now, write or serialize the whole object to that open file, so create BinaryFormatter class object first, and use its .Serialize() method which takes two arguments first the FileStream class object and the second is that object (here that object is of Employee class) which is to be written or serialized:
  BinaryFormatter bf = new BinaryFormatter();
  bf.Serialize(fs, emp);

Create a List of employee objects and Serialize them, See below:
    List<Employee> listEmployees = new List<Employee>();
    
Adding employee objects to list:         
      listEmployees.Add(emp);
      listEmployees.Add(emp2);
      listEmployees.Add(emp3);

Here, adding 4th employee object to list(this is another way of adding object to list):
      listEmployees.Add(new Employee(15,"Osama Sheikh"));

Now, the list have 4 objects in it so use loop to get the object from list and then serialize it.
      for (int i = 0; i < listEmployees.Count; i++)
      {
           Employee e = new Employee();

Casting each object from list to Employee then serialize it.    
           e = (Employee)listEmployees[i];
           bf.Serialize(fs, e);
           fs.FLush();
      }
}
 

0 comments: