Advertisement
ivandrofly

C# BinaryFormatter Serialization & Deserialization

Feb 19th, 2014
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.13 KB | None | 0 0
  1. using System;
  2. using System.Runtime.Serialization;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using System.IO;
  5.  
  6. namespace BinaryFormatter_Serialization
  7. {
  8.     class Program
  9.     {
  10.         static void Main()
  11.         {
  12.             Person person = new Person("Haim", 123123);
  13.             IFormatter binaryFormatter = new BinaryFormatter();
  14.  
  15.             using (FileStream stream = File.Create("personal.data"))
  16.             {
  17.                 binaryFormatter.Serialize(stream, person);
  18.             }
  19.  
  20.  
  21.             using (FileStream stream = File.OpenRead("personal.data"))
  22.             {
  23.                 Person objPerson = (Person)binaryFormatter.Deserialize(stream);
  24.                 Console.WriteLine(person);
  25.             }
  26.         }
  27.     }
  28.  
  29.     [Serializable]
  30.     class Person
  31.     {
  32.         private string name;
  33.         private int id;
  34.  
  35.         public Person(string nameVal, int idVal)
  36.         {
  37.             this.name = nameVal;
  38.             this.id = idVal;
  39.         }
  40.  
  41.         public override string ToString()
  42.         {
  43.             return string.Format("Name: {0}, ID: {1}", name, id);
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement