Skip to main content

C# Tutorial - Serialize Objects to a File [Beginner]


While storing information in memory is great, there comes a time your users will have to shut your application down. This means (probably) that you will need to write information to a file at some point, because you will want to store whatever data was in memory. Today, we are going to take a look at a feature built into .NET called Serialization that makes writing and reading data structures to and from a file extremely easy.

For this example, let's say I want to create a program that keeps track of all the cars my friends own. I'm going to create two objects to achieve this: Car and Owner. The Car object will store the make, model, and year of the car. The Owner object will save some information about who owns the car. Each Car object will hold a reference to an Owner object.
//information about the car
public class Car
{
   private string make;
   private string model;
   private int year;
   private Owner owner;

   public Car()
   {
   }
}

//information about the car's owner
public class Owner
{
   private string firstName;
   private string lastName;

   public Owner()
   {
   }
}
 
Since most of us have more than one friend, we're going to need to create a List of Car objects.
List<Car> cars = new List<Car>();
 
Now that we have our objects created, we're almost ready to serialize them. When I save data to files, I like to create an object specifically to hold all the things I want to serialize.
public class ObjectToSerialize
{
   private List<Car> cars;

   public List<Car> Cars
   {
      get { return this.cars; }
      set { this.cars = value; }
   }

   public ObjectToSerialize()
   {
   }
}
 
This class holds a reference to every object we'll want to serialize. In this case, the only thing we want to save is the list of cars. Now lets create the functions that will perform the serialization and deserialization of our object. I usually create a Serializer class to control the writing and reading to and from files.
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class Serializer
{
   public Serializer()
   {
   }

   public void SerializeObject(string filename, ObjectToSerialize objectToSerialize)
   {
      Stream stream = File.Open(filename, FileMode.Create);
      BinaryFormatter bFormatter = new BinaryFormatter();
      bFormatter.Serialize(stream, objectToSerialize);
      stream.Close();
   }

   public ObjectToSerialize DeSerializeObject(string filename)
   {
      ObjectToSerialize objectToSerialize;
      Stream stream = File.Open(filename, FileMode.Open);
      BinaryFormatter bFormatter = new BinaryFormatter();
      objectToSerialize = (ObjectToSerialize)bFormatter.Deserialize(stream);
      stream.Close();
      return objectToSerialize;
   }
}
 
As you can see, the actual code required to serialize an object is relatively small and simple. At this point, however, the code will not build. Before the Serialize function can be called on ObjectToSerialize we must include the Serializable attribute and it must implement the ISerializable interface.
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable()]
public class ObjectToSerialize : ISerializable
{
   private List<Car> cars;

   public List<Car> Cars
   {
      get { return this.cars; }
      set { this.cars = value; }
   }

   public ObjectToSerialize()
   {
   }

   public ObjectToSerialize(SerializationInfo info, StreamingContext ctxt)
   {
      this.cars = (List<Car>)info.GetValue("Cars", typeof(List<Car>));
   }

   public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
   {
      info.AddValue("Cars", this.cars);
   }
}
 
As part of the ISerializable interface, the class must include another constructor for deserializing the object and a function GetObjectData which describes how to serialize the object. Since the Car and Owner objects are also being serialized, they will also need to implement these functions.
[Serializable()]
public class Car : ISerializable
{
   private string make;
   private string model;
   private int year;
   private Owner owner;

   public Car()
   {
   }

   public Car(SerializationInfo info, StreamingContext ctxt)
   {
      this.make = (string)info.GetValue("Make", typeof(string));
      this.model = (string)info.GetValue("Model",typeof(string));
      this.year = (string)info.GetValue("Year", typeof(int));
      this.owner = (Owner)info.GetValue("Owner", typeof(Owner));
   }

   public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
   {
      info.AddValue("Make", this.make);
      info.AddValue("Model", this.model);
      info.AddValue("Make", this.year);
      info.AddValue("Owner", this.owner);
   }
}


[Serializable()]
public class Owner : ISerializable
{
   private string firstName;
   private string lastName;

   public Owner()
   {
   }

   public Owner(SerializationInfo info, StreamingContext ctxt)
   {
      this.firstName = (string)info.GetValue("FirstName", typeof(string));
      this.lastName = (string)info.GetValue("LastName", typeof(string));
   }

   public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
   {
      info.AddValue("FirstName", this.firstName);
      info.AddValue("LastName", this.lastName);
   }
}
 
Now, to save the list of objects to a file, all that needs to be done is to call the Serialize and DeSerialize functions of the Serializer class.
List<Car> cars = new List<Car>();

//save the car list to a file
ObjectToSerialize objectToSerialize = new ObjectToSerialize();
objectToSerialize.Cars = cars;

Serializer serializer = new Serializer()
serializer.SerializeObject("outputFile.txt", objectToSerialize);

//the car list has been saved to outputFile.txt
//read the file back from outputFile.txt

objectToSerialize = serializer.DeSerializeObject("outputFile.txt");
cars = objectToSerialize.Cars;
 
That is all that's required to save and load custom C# objects to a binary file. Just like any file, it is possible for your files to become corrupted. Because of this, it is probably a good idea to add some error handling whenever output from the file is being cast to an object.

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as