How to save/restore serializable object to/from file in C#?

How to save/restore serializable object to/from file in C#?

To save and restore a serializable object to/from a file in C#, you can use the BinaryFormatter or JsonSerializer class to serialize the object into binary or JSON format and write it to a file, and then deserialize it back from the file when needed. Here's how you can do it:

  • Using Binary Serialization (using BinaryFormatter): Binary serialization is used to convert an object into a binary format for storage.
using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; [Serializable] public class MySerializableClass { public int Id { get; set; } public string Name { get; set; } } public class Program { public static void Main() { MySerializableClass objToSerialize = new MySerializableClass { Id = 1, Name = "John" }; // Save the object to a file using binary serialization BinaryFormatter formatter = new BinaryFormatter(); using (FileStream fs = new FileStream("serialized_object.bin", FileMode.Create)) { formatter.Serialize(fs, objToSerialize); } // Restore the object from the file using binary deserialization MySerializableClass restoredObj; using (FileStream fs = new FileStream("serialized_object.bin", FileMode.Open)) { restoredObj = (MySerializableClass)formatter.Deserialize(fs); } Console.WriteLine("Restored Object - Id: " + restoredObj.Id + ", Name: " + restoredObj.Name); } } 
  • Using JSON Serialization (using JsonSerializer): JSON serialization is used to convert an object into a JSON format for storage.
using System; using System.IO; using System.Text.Json; [Serializable] public class MySerializableClass { public int Id { get; set; } public string Name { get; set; } } public class Program { public static void Main() { MySerializableClass objToSerialize = new MySerializableClass { Id = 1, Name = "John" }; // Save the object to a file using JSON serialization string json = JsonSerializer.Serialize(objToSerialize); File.WriteAllText("serialized_object.json", json); // Restore the object from the file using JSON deserialization string jsonFromFile = File.ReadAllText("serialized_object.json"); MySerializableClass restoredObj = JsonSerializer.Deserialize<MySerializableClass>(jsonFromFile); Console.WriteLine("Restored Object - Id: " + restoredObj.Id + ", Name: " + restoredObj.Name); } } 

Both methods will save the serializable object to a file and then restore it back when needed. Choose the serialization method (binary or JSON) based on your requirements and preferences. JSON serialization is more human-readable and can be used to share data with other systems, while binary serialization is more efficient in terms of file size and serialization/deserialization speed.

Examples

  1. "C# serialize object to file"

    // Code to serialize an object to a file using (FileStream stream = new FileStream("filename.dat", FileMode.Create)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, yourObject); } 
  2. "C# deserialize object from file"

    // Code to deserialize an object from a file using (FileStream stream = new FileStream("filename.dat", FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); YourObjectType yourObject = (YourObjectType)formatter.Deserialize(stream); } 
  3. "C# save serializable object to XML file"

    // Code to save a serializable object to an XML file XmlSerializer serializer = new XmlSerializer(typeof(YourObjectType)); using (TextWriter writer = new StreamWriter("filename.xml")) { serializer.Serialize(writer, yourObject); } 
  4. "C# load serializable object from XML file"

    // Code to load a serializable object from an XML file XmlSerializer serializer = new XmlSerializer(typeof(YourObjectType)); using (TextReader reader = new StreamReader("filename.xml")) { YourObjectType yourObject = (YourObjectType)serializer.Deserialize(reader); } 
  5. "C# JSON serialization and deserialization"

    // Code for JSON serialization string json = JsonConvert.SerializeObject(yourObject); File.WriteAllText("filename.json", json); // Code for JSON deserialization string json = File.ReadAllText("filename.json"); YourObjectType yourObject = JsonConvert.DeserializeObject<YourObjectType>(json); 
  6. "C# binary serialization example"

    // Code for binary serialization using (FileStream stream = new FileStream("filename.bin", FileMode.Create)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, yourObject); } 
  7. "C# binary deserialization example"

    // Code for binary deserialization using (FileStream stream = new FileStream("filename.bin", FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); YourObjectType yourObject = (YourObjectType)formatter.Deserialize(stream); } 
  8. "C# data contract serialization"

    // Code for data contract serialization DataContractSerializer serializer = new DataContractSerializer(typeof(YourObjectType)); using (FileStream stream = new FileStream("filename.xml", FileMode.Create)) { serializer.WriteObject(stream, yourObject); } 
  9. "C# data contract deserialization"

    // Code for data contract deserialization DataContractSerializer serializer = new DataContractSerializer(typeof(YourObjectType)); using (FileStream stream = new FileStream("filename.xml", FileMode.Open)) { YourObjectType yourObject = (YourObjectType)serializer.ReadObject(stream); } 
  10. "C# custom object serialization example"

    // Code for custom object serialization XmlSerializer serializer = new XmlSerializer(typeof(YourObjectType), new XmlRootAttribute("CustomRoot")); using (TextWriter writer = new StreamWriter("filename.xml")) { serializer.Serialize(writer, yourObject); } 

More Tags

singlechildscrollview reveal.js cucumber passport.js openxml-sdk multiple-matches logback coordinate mousehover spring-restcontroller

More C# Questions

More Housing Building Calculators

More Livestock Calculators

More Animal pregnancy Calculators

More Chemical thermodynamics Calculators