Click here to Skip to main content
Click here to Skip to main content

Object serialisation in C#

, 9 Apr 2012
Rate this:
Please Sign up or sign in to vote.
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.




The end!!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

F. ARO
Engineer
Lebanon Lebanon
Electronics, Telecommunications, Development, Music!
Follow on   Twitter

Comments and Discussions

 
QuestionPurpose of the tip is not clear to me... [modified] PinmemberAndreas Gieriet9-Apr-12 4:28 
AnswerRe: Purpose of the tip is not clear to me... PinmemberF. ARO9-Apr-12 5:13 
GeneralRe: Purpose of the tip is not clear to me... PinmemberAndreas Gieriet9-Apr-12 5:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140718.1 | Last Updated 9 Apr 2012
Article Copyright 2012 by F. ARO
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid