Binary serialization in C#

Serializing an object into a binary file is an easy and fast way to persist your objects. If binary serialization is used to cache objects normally read from an XML file, a database or some other file format, you’ll get even more benefits.

After incorporating binary serialization into a C# application that loaded data from an Excel spreadsheet, I was able to get a 33% decrease in execution time by caching the generated object into a binary file. It’s a quick-and-dirty way to get a speed increase especially when you’re loading a lot of external data that changes, but doesn’t change frequently.

The first step for serializing a class into a binary file is to mark the class as Serializable.

[Serializable]
public class YourClass
{
	// your class definition.
}

Now that your class is ready to be serialized, you can use ObjectSerializer. The ObjectSerializer class below allows anyone to serialize an object into a binary file. Serializing or de-serializing a class marked with the [Serializable] attribute takes no more than 3 lines of C# code.

public class ObjectSerializer<T>
{
	protected IFormatter iformatter;

	public ObjectSerializer()
	{
		this.iformatter = new BinaryFormatter();
	}

	public T GetSerializedObject(string filename)
	{
		if (File.Exists(filename))
		{
			Stream inStream = new FileStream(
				filename,
				FileMode.Open,
				FileAccess.Read,
				FileShare.Read);
			T obj = (T)this.iformatter.Deserialize(inStream);
			inStream.Close();
			return obj;
		}
		return default(T);
	}

	public void SaveSerializedObject(T obj, string filename)
	{
		Stream outStream = new FileStream(
			filename,
			FileMode.Create,
			FileAccess.Write,
			FileShare.None);
		this.iformatter.Serialize(outStream, obj);
		outStream.Close();
	}
}

To serialize an object using ObjectSerializer, first instantiate the ObjectSerializer class. Then use the SaveSerialziedObject() method to serialize the object.

YourClass yourObject = new YourClass();
ObjectSerializer<YourClass> objSerializer =
	new ObjectSerializer<YourClass>();

// serializes yourClass to SomeFilename.bin.
objSerializer.SaveSerializedObject(yourObject, "SomeFilename.bin");

To deserialize the binary file generated from the previous operation, instantiate the ObjectSerializer class. Then use the GetSerializedObject() method to retrieve the original object.

ObjectSerializer<YourClass> objSerializer =
	new ObjectSerializer<YourClass>();

// deserializes yourClass from SomeFilename.bin.
YourClass yourObjectFromFile =
	objSerializer.GetSerializedObject("SomeFilename.bin");

And there you have it… quick-and-dirty binary serialization in C#!

Tags:

Leave a Reply