Object Serialization


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. namespace MyObjSerial
  2. {
  3. [Serializable()] //Set this attribute to all the classes that want to serialize
  4. public class Employee : ISerializable //derive your class from ISerializable
  5. {
  6. public int EmpId;
  7. public string EmpName;
  8.  
  9. //Default constructor
  10. public Employee()
  11. {
  12. EmpId = 0;
  13. EmpName = null;
  14. }
  15. }
  16.  
  17. //Deserialization constructor.
  18. public Employee(SerializationInfo info, StreamingContext ctxt)
  19. {
  20. //Get the values from info and assign them to the appropriate properties
  21. EmpId = (int)info.GetValue("EmployeeId", typeof(int));
  22. EmpName = (String)info.GetValue("EmployeeName", typeof(string));
  23. }
  24.  
  25. //Serialization function.
  26. public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
  27. {
  28. //You can use any custom name for your name-value pair. But make sure you
  29. // read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
  30. // then you should read the same with "EmployeeId"
  31. info.AddValue("EmployeeId", EmpId);
  32. info.AddValue("EmployeeName", EmpName);
  33. }
  34. }
  35.  
  36.  
  37.  
  38. // Serialize Sample
  39. Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
  40. BinaryFormatter bformatter = new BinaryFormatter();
  41.  
  42. Console.WriteLine("Writing Employee Information");
  43. bformatter.Serialize(stream, mp);
  44. stream.Close();
  45.  
  46. // Deserialize Sample
  47. mp = null;
  48.  
  49. //Open the file written above and read values from it.
  50. stream = File.Open("EmployeeInfo.osl", FileMode.Open);
  51. bformatter = new BinaryFormatter();
  52.  
  53. Console.WriteLine("Reading Employee Information");
  54. mp = (Employee)bformatter.Deserialize(stream);
  55. stream.Close();
  56.  
  57. Console.WriteLine("Employee Id: {0}",mp.EmpId.ToString());
  58. Console.WriteLine("Employee Name: {0}",mp.EmpName);

URL: http://www.codeproject.com/csharp/objserial.asp

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.