+92 332 4229 857 99ProjectIdeas@Gmail.com

How to read object from file (Serialization) (C#.net)


How to read object from file (Serialization):
Serialization, as implemented in the System.Runtime.Serialization namespace is the process of serializing and de-serializing objects so that they can be stored or transferred and then later re-created.  
Deserializing is the process of converting a previously serialized sequence of bytes into an object.
  
Code
 
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
 
In the previous example of "How to write a object in file" we see an Employee class object is written in file. Now how to read that written object from file is:

READING A SINGLE OBJECT FROM FILE:
 
 Reading a single object from file and display its id and name on console:
       
     FileStream fs = new FileStream("abc.dat", FileMode.Open, FileAccess.Read);
     BinaryFormatter bf = new BinaryFormatter();

Here, casting each object to Employee while Deserializing:

        Employee emp = (Employee)bf.Deserialize(fs);

.print() method is Employee class method which displays id and name on console:

        emp.print();


READING ALL OBJECTS FROM FILE:
 
Reading whole file and load all objects of Employee class from file, and add that objects to  List of Employee objects.
 
List<Employee> listEmployees = new List<Employee>();
FileStream fs = new FileStream("abc.dat", FileMode.Open, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();

       while (fs.CanRead)
       {
            Employee emp = (Employee)bf.Deserialize(fs);
            listEmployees.Add(emp);
       }

Now, whole objects loaded in listEmployees. You can do whatever with the objects and can write back also.
 
DISPLAYING ALL LOADED OBJECTS FROM LIST:
 
        foreach (Employee emp in listEmployees)
               emp.print();

 
 

0 comments: