Object serialisation in C#
General object serialization,
Introduction
I needed to serialize objects without entering or analyzing their class
structures, definitions, and fields...
I found answer on codeproject, about converting an object to byte[].
then used it to serialize objects in xml by applying base64string conversions to their byte[] equivalent.
Background
If the object class has references to other classes (as it
probably does) then you need to include those as well.
My used way was to transform the object to a
byte[].
Save bytes[] as base64string in an xml file.
Also reading or creating the object is by getting its base64string
Converting it in a byte[] than deserialysing the byte to its
object.
Using the code
There is two important things to do : Serialize and Deserialize
1. add the namespace: using
System.Runtime.Serialization.Formatters.Binary;
2. add [Serializable] attribute to your object class (Recommended);
3. as
example let assume class Client
[Serializable]
class Client
{
public Client(string name, int age, Bitmap photo)
{
Name = name;
Age = age;
Photo = photo;
}
public string Name
{
get;set;
}
public int Age
{
get;set;
}
public Bitmap Photo
{
get;set;
}
}
Now, to Serialize a Client 'Obj' : transform it to byte[] using binary formatter :
private static byte[] ToByteArray(object o) //byte[] b = ToByteArray(Obj)
{
var stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, o);
return stream.ToArray();
}
Then convert the Client 'Obj' byte[] to a base64string and add it to your XML using:
private static void Serialize(object o) //Serialize(Obj)
{
byte[] b = ToByteArray(o);
string client = Convert.ToBase64String(b);
DataRow dr = ds.Tables[0].NewRow();
dr[0] = client;
ds.Tables[0].Rows.Add(dr);
ds.WriteXml("Feed.xml");
}
//in our case to add a client for example :
// string photo_path = "./image.png";
// Serialize(new Client(txt_name.text,int.Parse(txt_age.text),new Bitmap(photo_path));
Now, Deserializing the object needs :1.reading the base64string from a datarow from XmlFile (or your source), and convert it to byte[];
2. deserialising the byte[] it using the binary formatter;
private static object DeSerialize(int rowindex ) //DeSerialize(listbox.Selecteindex)
{
byte[] b = Convert.FromBase64String(ds.Tables[0].Rows[rowindex][0].ToString());
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream(b);
object obj = bf.Deserialize(ms);
return obj;
}
//on the event listbox selected index changed you can use for example:
//Client CL = DeSerialyse(int rowindex);
//lbl_age.text=CL.Age.toString();
//picturebox.image=CL.Photo;
Filling the listbox by Clients Name:1.loop all the datarows from the dataset and deserialise every client
and add his name to a list<string> using deserialyse functions .
2.then choose listbox datasource the list of names.