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.
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(); } }
ÿÿÿÿ
AConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null ConsoleApp.Demo
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(); } }
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!