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
Release: 2023-09-05 15:53:02
forward
1441 people have browsed it

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();
   }
}
Copy after login

Output

ÿÿÿÿ
Copy after login

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();
   }
}
Copy after login

Output

ApplicationName Binary Serialize --- ApplicationId 1001
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template