C# – Serialize and deserialize data

When I wrote a small application with Client-Server model which sends data over TCP socket, I would like to build an intelligent way which serialize all of my data into stream, send this stream over socket and deserialize it back at server/client site. Using serialization all of data will be stored in stream or byte array and it is completely suitable for communicating over socket. To convert our object into stream using serialization is pretty simple. In this small example below, I would like to illustrate how we can serialize our object.

The example is a small management application which manages person with their information. To simplify the problem, we restrict the number of member only until 10 persons and manage them in a list

private const int cnstMax = 10;
private Person[] m_pList = new Person[cnstMax];
private int m_nPos = 0;

Class Person indicates and contains all of information of a member. It will be set with [Serializable] Attribute so that we can serialize it later. This attribute is a condition so that the serialize process runs smoothly later, without setting this attribute we can not serialize this type.

[Serializable]
private class Person
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public DateTime DateOfBirth { get; set; }
	public bool Student { get; set; }
}

Through the components in dialog we can add,edit more members in our database and the serialization comes at the end with closing dialog. We will flush all data in member list into stream and store in a file.

private void SaveToFile()
{
	FileStream fsData = new FileStream("Person.dat", FileMode.OpenOrCreate, FileAccess.Write);
	BinaryFormatter bfFormatter = new BinaryFormatter();
	for (int nIndex = 0; nIndex < cnstMax; nIndex++)
	{
		bfFormatter.Serialize(fsData, m_pList[nIndex]);
	}
	fsData.Close();
}

BinaryFormatter class serializes and deserializes an object, or an entire graph of connected objects, in binary format. Besides of this serialization there is still xml serialization but I find binary serialization is much more common. We can apply it for any case requiring serialization. To deserialize the data back, just read data from file back to stream and restore all information back with type of Person.

private void ReadFromFile()
{
	FileStream fsFile = new FileStream("Person.dat", FileMode.OpenOrCreate, FileAccess.Read);
	BinaryFormatter bfFormatter = new BinaryFormatter();
	if (fsFile.Length > 0)
	{
		for (int nIndex = 0; nIndex < cnstMax; nIndex++)
		{
			m_pList[nIndex] = (Person)bfFormatter.Deserialize(fsFile);
		}
		fsFile.Close();
	}
}

Using serialization we can save a lot of time for processing data. You can download code here “Serialize and deserialize data“.

Update on 15.02.2010

If you want to use XMLSerializer to serialize your data as example above, we can adjust some settings so that it works.
First, our serialized class must define a constructor without any parameter. That means we should add some code line for this constructor

[Serializable]
public class Person
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public DateTime DateOfBirth { get; set; }
	public bool Student { get; set; }
	public Person()
	{
		FirstName = "";
		LastName = "";
		DateOfBirth = DateTime.Parse("01.01.1900");
		Student = false;
	}
	public Person(string First, string Last, DateTime Date, bool Stu)
	{
		FirstName = First;
		LastName = Last;
		DateOfBirth = Date;
		Student = Stu;
	}
}

Second the accessible level of class should be changed to public. And class call XMLSerializer to serialize and deserialize data as following

private void ReadFromFile()
{
	try
	{
		FileStream fsFile = new FileStream("Person.dat", FileMode.OpenOrCreate, FileAccess.Read);
		if (fsFile.Length > 0)
		{
			XmlSerializer xmls = new XmlSerializer(typeof(Person[]));
			m_pList = (Person[])xmls.Deserialize(fsFile);
			fsFile.Close();
		}
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
	}

}

private void SaveToFile()
{
	try
	{
		FileStream fsData = new FileStream("Person.dat", FileMode.OpenOrCreate, FileAccess.Write);
		XmlSerializer xmls = new XmlSerializer(typeof(Person[]));
		xmls.Serialize(fsData, m_pList);
		fsData.Close();
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *