Home >Backend Development >C#.Net Tutorial >What is binary serialization and deserialization in C# and how to implement binary serialization in C#?

What is binary serialization and deserialization in C# and how to implement binary serialization in C#?

PHPz
PHPzforward
2023-09-05 15:53:021504browse

What is binary serialization and deserialization in C# and how to implement binary serialization in C#?

Converting an object into an unreadable binary format is called binary serialization.

Converting a binary format back to a readable format is called deserialization?

To implement binary serialization in C# we have to use the library System.Runtime.Serialization.Formatters.Binary Assembly.

Create an object of the BinaryFormatter class and use the 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.Demok__BackingField-k__BackingField Binary Serialization

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

The above is the detailed content of What is binary serialization and deserialization in C# and how to implement binary serialization in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Collections in C#Next article:Collections in C#