Click here to Skip to main content
15,891,136 members
Articles / Programming Languages / C#
Tip/Trick

Object serialisation in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
9 Apr 2012CPOL1 min read 22.9K   241   9   3
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

C#
[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 :

C#
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: 

C#
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;

C#
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.


Image 1

Image 2

The end!!

License

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


Written By
Architect
Lebanon Lebanon
Bitcoin, Ethereum - Smartcontracts, Full Stack, Architecture & Development, Music!

Comments and Discussions

 
QuestionPurpose of the tip is not clear to me... Pin
Andreas Gieriet9-Apr-12 4:28
professionalAndreas Gieriet9-Apr-12 4:28 
AnswerRe: Purpose of the tip is not clear to me... Pin
F. Aro9-Apr-12 5:13
professionalF. Aro9-Apr-12 5:13 
GeneralRe: Purpose of the tip is not clear to me... Pin
Andreas Gieriet9-Apr-12 5:48
professionalAndreas Gieriet9-Apr-12 5:48 
Hi F.ARO,

1st advise: I'd like to talk to people with proper names (ARO13 is not a name, and usually I simply ignore such post where one can not stand to its identity) Wink | ;-)
2nd advise: no texting slang (looks childish) - this are articles and discussions, not chat Wink | ;-)
3rd advise: give initial two or three sentences (a concise abstract) that tells me as a reader if it is worth to read your text.
4th advise: learn on why and how to use using(...) { ... }, e.g.
C#
public abstract class Base64Codec<TObject> where TObject: class
{
    public static string Encode(TObject inst)
    {
        using (var ms = new MemoryStream())
        {
            new BinaryFormatter().Serialize(ms, inst);
            return Convert.ToBase64String(ms.ToArray());
        }
    }
    public static TObject Decode(string s)
    {
        using (var ms = new MemoryStream(Convert.FromBase64String(s)))
        {
            return new BinaryFormatter().Deserialize(ms) as TObject;
        }
    }
}


Cheers
Andi

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

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