Quick code snippet to show serialization of a class to a binary file called data.bin.

Two points to note; 1) The constructor on the class must be parameter-less and 2) the class (and all sub-classes) must be marker as [Serializable].

using System.Runtime.Serialization.Formatters.Binary;

using (Stream stream = File.Open("./data.bin", FileMode.Create))
{
var bin = new BinaryFormatter();
bin.Serialize(stream, classToSerialize);
stream.Close();
}

 

 

Advertisements