C# - File Serialization and Deserialization

File serialization and deserialization are essential methods for saving and loading object information into and out of files, respectively. They allow you to persist data across application sessions and even transfer data between different systems. C# provides built-in support for various serialization formats such as XML, JSON, and binary. Let's explore how to use file serialization and deserialization, as well as serialization attributes:

1. Saving and Loading Object Data:

To save object data to a file, you need to serialize the object into a format that can be written to a file. To load the data back into objects, you need to deserialize the file contents back into their original objects.

2. Using Serialization Techniques:

In C#, there are various ways serialization ways to save data, and each has its own strengths and situations where it's handy. Here are some commonly used serialization formats:

  • XML Serialization: This format uses XML (Extensible Markup Language) to represent object data. It's human-readable and widely supported.
  • JSON Serialization: JSON, short for JavaScript Object Notation, is a popular and lightweight way to swap data. It's smaller than XML and simple for people and computers to understand. Binary Serialization, on the other hand, saves object info in a small, compressed way.
  • Binary Serialization: Binary serialization is used to store object data in a compact binary format. It is efficient in terms of space and time but not human-readable.

Below is an example of how to use JSON serialization and deserialization using the System.Text.Json namespace, available in .NET Core 3.1 and later:


using System;
using System.IO;
using System.Text.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static class SerializationExample
{
    public static void Main()
    {
        // Sample object
        var person = new Person { Name = "John Doe", Age = 30 };

        // Serialize to JSON and save to a file
        string json = JsonSerializer.Serialize(person);
        File.WriteAllText("person.json", json);

        // Deserialize from JSON and load from the file
        string jsonString = File.ReadAllText("person.json");
        var loadedPerson = JsonSerializer.Deserialize(jsonString);

        Console.WriteLine($"Loaded Person: {loadedPerson.Name}, Age: {loadedPerson.Age}");
    }
}

3. Working with Serialization Attributes:

Serialization attributes allow you to customize the serialization and deserialization process. Two common serialization attributes are:

  • [Serializable]: This attribute is used with binary serialization and allows objects to be serialized and deserialized using the BinaryFormatter.
  • [DataContract] and [DataMember]: These attributes are used with XML and JSON serialization in Windows Communication Foundation (WCF) scenarios. In a class they enable selective serialization of properties.

Here's an example using '[Serializable]' attribute:


using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static class SerializationExample
{
    public static void Main()
    {
        // Sample object
        var person = new Person { Name = "John Doe", Age = 30 };

        // Serialize to binary and save to a file
        IFormatter formatter = new BinaryFormatter();
        using (Stream stream = new FileStream("person.dat", FileMode.Create, FileAccess.Write, FileShare.None))
        {
            formatter.Serialize(stream, person);
        }

        // Deserialize from binary and load from the file
        using (Stream stream = new FileStream("person.dat", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            var loadedPerson = (Person)formatter.Deserialize(stream);
            Console.WriteLine($"Loaded Person: {loadedPerson.Name}, Age: {loadedPerson.Age}");
        }
    }
}

Serialization attributes give you control over the serialization process, allowing you to include or exclude certain properties and fields from being serialized or to specify alternative names for serialized properties.

Serialization and deserialization are helpful ways to save data in C#. Remember to pick the right way to save, and use special codes when necessary to customize how the saving works.