Read Binary Using BinaryFormatter Class In C#

This snippet opens a binary file for reading. It deserializes the object array stored in the binary file using the BinaryFormatter Class and displays the data to the console.


  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. class Program
  5. {
  6.     static void Main(string[] args)
  7.     {
  8.         Stream bStream = File.Open("file.bin", FileMode.Open);
  9.         BinaryFormatter bFormater = new BinaryFormatter();
  10.         object[] contact = (object[])bFormater.Deserialize(bStream);
  11.         for (int i = 0; i < contact.Length; i++)
  12.         {
  13.             object[] employee = (object[])contact[i];
  14.             Console.WriteLine("First Name: " + employee[0]);
  15.             Console.WriteLine("Surname: " + employee[1]);
  16.         }
  17.         Console.ReadKey();
  18.     }
  19. }

No comments:

Post a Comment