RSS
 

Archive for June, 2010

Quick Serialization of an Object in C#

23 Jun

Sometimes I just post code snippets for myself.

Serializing 2 objects

try
{
	BinaryFormatter bf = new BinaryFormatter();
	using (Stream output = File.OpenWrite("File.txt")){
		bf.Serialize(output, object1);
		bf.Serialize(output, object2);
	}
}
catch (Exception ex)
{
	MessageBox.Show("Unable to save the file\r\n" + ex.Message,
	"File Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

De-serializing the file

try
{
	BinaryFormatter bf = new BinaryFormatter();
	using (Stream output = File.OpenRead(openDialog.FileName)){
		object1 = (object1)bf.Deserialize(output);
		object2  = (object2)bf.Deserialize(output);
	}
}
catch (Exception ex)
{
	MessageBox.Show("Unable to read the file\r\n" + ex.Message,
	"File Open Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
 
No Comments

Posted in C#