What is Binary Serialization and Deserialization in C# and how to achieve Binary Serialization in C#?

CsharpServer Side ProgrammingProgramming

Converting an Object to a Binary format which is not in a human readable format is called Binary Serialization.

Converting back the binary format to human readable format is called deserialization?

To achieve binary serialization in C# we have to make use of library System.Runtime.Serialization.Formatters.Binary Assembly

Create an object of BinaryFormatter class and make use of serialize method inside the class

Example

Serialize an Object to Binary
[Serializable]
public class Demo {
   public string ApplicationName { get; set; } = "Binary Serialize";
   public int ApplicationId { get; set; } = 1001;
}
class Program {
   static void Main()    {
      Demo sample = new Demo();
      FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat", FileMode.Create);
      BinaryFormatter formatter = new BinaryFormatter();
      formatter.Serialize(fileStream, sample);
      Console.ReadKey();
   }
}

Output

ÿÿÿÿ

AConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null ConsoleApp.Demo<ApplicationName>k__BackingField-<ApplicationId>k__BackingField Binary Serializeé

Example

Converting back from Binary to Object
[Serializable]
public class Demo {
   public string ApplicationName { get; set; }
   public int ApplicationId { get; set; }
}
class Program {
   static void Main()    {
      FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat ", FileMode.Open);
      BinaryFormatter formatter = new BinaryFormatter();
      Demo deserializedSampledemo = (Demo)formatter.Deserialize(fileStream);
      Console.WriteLine($"ApplicationName { deserializedSampledemo.ApplicationName} --- ApplicationId       { deserializedSampledemo.ApplicationId}");
      Console.ReadKey();
   }
}

Output

ApplicationName Binary Serialize --- ApplicationId 1001
raja
Published on 05-Aug-2020 11:57:32
Advertisements