How do you serialize and save an object to a binary file?
How do you serialize and save an object to a binary file?
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
Anubhav Kumar
23-May-2025To serialize and save an object to a binary file in C#, you can use the
BinaryFormatter
class (for legacy .NET Framework) orSystem.Text.Json
orSystem.Runtime.Serialization.Formatters.Binary
with caution.1. Binary Serialization (Legacy, .NET Framework)
To deserialize:
Warnings:
BinaryFormatter
is insecure for untrusted data.2. Use
System.Text.Json
(Recommended for modern apps, JSON format)For safety and cross-platform compatibility:
To deserialize:
3. Use
FileStream
andBinaryWriter
(Manual Binary Writing)If you want custom binary serialization:
And to read it back:
Summary