- Course
- Data serialization
- BinaryFormatter: Binary serialization
BinaryFormatter: Binary serialization
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a C# program to serialize and deserialize objects in binary format. To do this you can use the BinaryFormatter
class included in the System.Runtime.Serialization
namespace.
First implement a Person class with three properties (Name, Age and City). The City class will have two properties (Name and Population). Then create a person object and use the BinaryFormatter
object's serializer to save the data in a binary file, later deserialize the file and print it on screen. Remember to prepare a ToString ()
method to print the Persona class.
Input
Output
Solution
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
public class BinarySerializer
{
static string nameFile = "out.json";
public static void Main(string[] args)
{
Person person = new Person(){ Name = "Nauj", Age = 26, City = new City(){ Name = "Spain", Population = 13456766 } };
Serialize(person);
person = Deserialize();
Console.WriteLine(person.ToString());
}
public static void Serialize(Person p)
{
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream(nameFile,
FileMode.Create, FileAccess.Write, FileShare.None))
{
formatter.Serialize(stream, p);
}
}
public static Person Deserialize()
{
Person p;
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream(nameFile,
FileMode.Open, FileAccess.Read, FileShare.Read))
{
p = (Person)formatter.Deserialize(stream);
}
return p;
}
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public City City { get; set; }
public override string ToString()
{
StringBuilder str = new StringBuilder();
str.AppendLine("Name: " + Name);
str.AppendLine("Age: " + Age);
str.AppendLine("City: " + City.Name);
return str.ToString();
}
}
[Serializable]
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
}