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

Object Serialization using C#

By , 31 Jan 2002
 

Introduction

Writing crucial data to the disk as TEXT is always dangerous. Any anonymous user can open the text file and easily read your data. With Object Serialization, you can reduce this danger to a certain extent. You can write any complex object directly to a filestream without converting values of individual properties into a text. You can make the data written, to the disk, atleast not human readable. In order for the users to read your data files, they have to use your program. Like a File Open command which you may provide in your application.

.NET and Object Serialization

Now what does .NET framework provide us to do Serialization of Custom-build class objects? With the advent of any programming language, developers would first look whether it is an OOPL. If so, how to create my own classes with my own properties and functions. And then comes inheritance and all others. Explaining how to create user-defined classes is out of scope of this article. But along the way you will get to know about what a user-defined class is.

Serialization explained

Serialization is the process of converting complex objects into stream of bytes for storage. Deserialization is its reverse process, that is unpacking stream of bytes to their original form. The namespace which is used to read and write files is System.IO. For Serialization we are going to look at the System.Runtime.Serialization namespace. The ISerializable interface allows you to make any class Serializable.

Here are the following steps that we are going to do to create a serializable class and test it.

  • Create a custom class named Employee and assign properties.
  • Define the serialization functions.
  • Create a main class and instantiate our Employee class.
  • Serialize the object to a sample file.
  • Deserialize the values by reading it from the file.

Defining Employee class and properties

Our custom class Employee should be derived from the ISerializable interface and should hold the Serializable attribute. Here is the code snippet.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace MyObjSerial
{
    [Serializable()]    //Set this attribute to all the classes that want to serialize
    public class Employee : ISerializable //derive your class from ISerializable
    {
        public int EmpId;
        public string EmpName;
        
        //Default constructor
        public Employee()
        {
            EmpId = 0;
            EmpName = null;
        }
        }
}

Define Serialization functions

Now we need two functions: One to say how to serialize Employee objects and another to say how to deserialize them. For serialization we override the GetObjectData() function provided by the ISerializable interface. For deserialization we provide a special constructor with the serialization parameters as arguments. This constructor will be called when we deserialize our file to object (which will be shown later).

One of the important parameters is the SerializationInfo object. This object holds a name-value pair for the properties to be serialized. You can decide which property should be serialized and which not in the GetObjectData() function. All the properties that are added to this SerializationInfo parameter will be serialized. Here are the codes for the two functions. Add them to our Employee class.

//Deserialization constructor.
public Employee(SerializationInfo info, StreamingContext ctxt)
{
    //Get the values from info and assign them to the appropriate properties
    EmpId = (int)info.GetValue("EmployeeId", typeof(int));
    EmpName = (String)info.GetValue("EmployeeName", typeof(string));
}
        
//Serialization function.
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
    //You can use any custom name for your name-value pair. But make sure you
    // read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
    // then you should read the same with "EmployeeId"
    info.AddValue("EmployeeId", EmpId);
    info.AddValue("EmployeeName", EmpName);
}
Thats it. You have created your own class which is now serializable. Now lets see how to write an instance of Employee to a special file with a custom .osl extension. And we also see how to read back Employee object from the file.

Create a main class and instantiate our Employee class

Following is the code snippet for ObjSerial class which holds our application's main entry point.
//Main class
public class ObjSerial
{
    public static void Main(String[] args)
    {
        //Create a new Employee object
        Employee mp = new Employee();
        mp.EmpId = 10;
        mp.EmpName = "Omkumar";
                
        //Add code below for serialization
    }
}

Serialize the object to a sample file

For serializing, lets open a stream object and give a sample file name EmployeeInfo.osl. Note, the demo exe file has this same name. So when you run ObjSerial.exe, the EmployeeInfo.osl file will be created under the folder where you copied the exe file. Add the following code to our ObjSerial class. Once a stream is open we create a BinaryFormatter and use the Serialize method to serialize our object to the stream. What Serialize method would do? It converts our object into binary format and streams it in.
            
// Open a file and serialize the object into it in binary format.
// EmployeeInfo.osl is the file that we are creating. 
// Note:- you can give any extension you want for your file
// If you use custom extensions, then the user will now 
//   that the file is associated with your program.
Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
            
Console.WriteLine("Writing Employee Information");
bformatter.Serialize(stream, mp);
stream.Close();

Deserialize the values by reading it from the file

Now we read the created file and cast the return value to our Employee class for further usage. For reading we again create a BinaryFormatter to read the object in binary form. We then use the Deserialize method which converts the stream of bytes to an Object object. This object can then be easily casted to our Employee class.
//Clear mp for further usage.
mp = null;
            
//Open the file written above and read values from it.
stream = File.Open("EmployeeInfo.osl", FileMode.Open);
bformatter = new BinaryFormatter();
        
Console.WriteLine("Reading Employee Information");
mp = (Employee)bformatter.Deserialize(stream);
stream.Close();
            
Console.WriteLine("Employee Id: {0}",mp.EmpId.ToString());
Console.WriteLine("Employee Name: {0}",mp.EmpName);

Conclusion

This sample application explains the core part of serialization only. Actually you can do a lot with the objects while serializing and deserializing. Now you can create a Mulitple document application with .NET Windows Forms and go ahead Serialize the world into your disk.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

omkamal
Web Developer
United States United States
Member
Started programming with computers in 1995. Ever since it keeps me busy and creative. Did a bachelor's degree in electronics and communication only to better understand the inside of computers and its power. Currently working as a software developer in US and looking for a girl-friend...

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermanoj kumar choubey25 Apr '13 - 1:22 
Nice
QuestionCare with ENUM typesmemberOscar Miras29 Nov '12 - 2:13 
Be sure to retrieve enum types from serialized object this way:
 
m_enumMember= (ENUM_TYPE)info.GetValue("fieldName", typeof(int));
 
If not, it will raise an Exception; informing that "fieldName" can't be found.
QuestionDeserializememberingvare14 Nov '12 - 2:18 
I receive serialized menu objects generated in C#.
 
Now I want to deserialize it in J2ME using JiBX.  
feels like there is a XML format difference. JiBX expects a very conventional XML-structure
and need both a XML data document and a XML Binding document.
 
Seems incompatible
GeneralMy vote of 5memberTem Rhythm11 Sep '12 - 21:52 
Thanks for the article. It's help for me to understand serialization in practice
Questionserializationmemberjingdedi21 Aug '12 - 23:07 
cool post. really helped me solved my problem
 
Thanks!
jingdedi
GeneralMy vote of 5memberAkiii0018 Jun '12 - 5:08 
good description !
Suggestion[My vote of 2] My vote of 2 - dangerousmemberandyclap23 Jan '12 - 0:20 
While I have no complaints about the article's code - I have a big complaint about the author positioning this as a method for implementing security.
 
Secutrity through obscurity is not security. And I would hardly call knowlege of .net serialization obscure.
 
If the focus here is really on security, the author should show serialization to a memory stream then using a cryptographic provider to encrypt this data before writing it out, and vice versa.
 
If it's just about serialization, then perhaps the introduction should focus on this being simply more convenient than creating your own serializer/deserializer framework.
And in this case the example could be even simpler if it were to make use of the standard serializers and the Serializable attribute. ISerializable is really for where you need to override standard serialization.
GeneralMy vote of 5memberSergiy Tkachuk15 Dec '11 - 19:21 
Simple and helpful
QuestionData is readablememberS.Reda30 Jun '11 - 1:55 
When you open the file you will be able to see the data that you serialized in the file!!
How come? We want the data not to be readable for the user.
Please help.
GeneralMy vote of 4membershankaranarayana18 May '11 - 0:14 
katte
GeneralAnother great site with info on serializationmemberjonarnar24 Apr '11 - 2:51 
Check out http://programming.flashadventures.com/c-sharp/writing-objects-to-files-serialization/
 
It has really easy to understand examples Smile | :)
QuestionHow to De-serialize whole array or list of ojbectsmemberMushtaq Muhammad3 Apr '11 - 0:06 
Hi, Good simple work to define the serialization process in C#. Can you please explain how can we De-serialize whole array or list of objects?
Mushtaq Muhammad

AnswerRe: How to De-serialize whole array or list of ojbectsmemberjonarnar24 Apr '11 - 2:52 
Check out the link I just posted:
http://programming.flashadventures.com/c-sharp/writing-objects-to-files-serialization
QuestionGreat, exactly what I needed though I have a small questionmemberIlanF25 Mar '11 - 1:29 
When serializing an object I found it leaves traces of the object in the file that could be read with a simple text editor.
Well I tried to serialize an object and opened the file with notepad and this is what I got:
Click For Image
 
For what I need it, I need that the data could not be read with normal text editor but only by my app, what can I do?
GeneralMy vote of 4memberdendrit6 Dec '10 - 1:15 
although it's brief it's useful information
GeneralMy vote of 5memberNithin Sundar25 Nov '10 - 17:34 
Excellent article. Really got a beginner like me get started in object File I/O.
GeneralMy vote of 5memberSayem Ahmed2 Oct '10 - 19:28 
Nice article.
QuestionHow images are serilized?memberMember 471108727 Sep '10 - 2:10 
If my class has an Image property defined by reference. Does the serilizing process as you described embed that image
inside the saved file so I will be able restore that image without having the initial source?
GeneralThe article is complete but far from perfectmemberSimon Dufour14 Jul '10 - 4:18 
The article contains all the information to serialize an object. It should contains more link to valuable information. It wasn't true that you NEEDED to use a binary writer. Explaining that part a bit would have been better.
 
For a refresh however, it's good enough. For beginners, I suggest you search a little bit for more info on all the objects you will use while doing the serialization. Particularly the part on Writers and Streams.
 
Here's 3-parts in-depth articles from the MSDN Magazine on Serialization.
 
Run-time Serialization

Part 1
 
Part 2
 
Part 3
AnswerRe: The article is complete but far from perfectmemberMazen el Senih6 Apr '12 - 4:47 
Thank you sir for this suggestions,It made me very glad to see these references after having troubles with advanced serialization lifetime .. Thumbs Up | :thumbsup:
There is always hope ..!

GeneralThanksmemberxliqz4 Feb '10 - 7:01 
Thank you for the great article!
GeneralfilehandlingmemberM.YASIR ALI7 Dec '09 - 10:33 
plz told me what is difference between text file and binary file in filehandling just define it
GeneralNicememberNitin Sawant30 Nov '09 - 22:15 
Nice
 
=============
NITIN SAWANT
=============

Generalexcellent!memberalejandro29A28 Aug '09 - 2:54 
simple and direct Thumbs Up | :thumbsup:
 
Dios existe pero duerme...
Sus pesadillas son nuestra existencia.
(Ernesto Sabato)

GeneralAwesomememberAnubisasc19 Jan '09 - 5:33 
I have been looking for a way to Serialize my custom controls and this is great.
 
Thanks!
GeneralISerializable, inheritance and GetObjectDatamemberdevvvy9 Jan '09 - 14:09 
hello
Having a bit of trouble trying to implement Serializable

[Serializable()]
class Parent : ISerializable
{
...
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
...
return;
}
...
}
 
[Serializable{}]
class Derived : Parent, ISerializable
{
...
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// TROUBLE HERE! Compile won't let me! Actually base.GetObjectData for some reason is not even visible from Intellisense?
base.GetObjectDate(info, context);
return;
 
//Also tried, compile error: Use of keyword 'base' is not valid in this context
((ISerializable)base).GetObjectData(info, context);
 
}
...
}

 
Any suggestion please?
 
Thanks
 
dev

GeneralRe: ISerializable, inheritance and GetObjectDatamemberdevvvy9 Jan '09 - 15:02 
Answer here: http://msdn.microsoft.com/en-us/library/ms182326(VS.80).aspx[^]
 
dev

QuestionCan I serialize whole object to xml?memberjeff wa27 Dec '08 - 11:50 
I want to Create a class (call it FormElement). That class should have some properties like the metadata they have with data elements like (name, sequence number, value—which is just a string, etc).
 
This class has as attributes of type Validation Application Block Validation classes.
 
Make sure the class you define is serializable. Serialize it to xml and deserialize it. Verify that all properties of the class including the validation application block attributes survive serialization.
QuestionWhat are the reasons to Serializememberexpresso10001 Oct '08 - 4:18 
You should list several reasons why to serialize, not just to protect data. Give some real world intents or situations where you would want to Serialize
 
C# Software Developer

AnswerRe: What are the reasons to SerializememberAram Azhari30 Dec '08 - 4:37 
I use serialization for communicating between Client and Servers while using sockets.
Since sockets can send and receive only a buffer of Bytes, you can create your object on one side and send it with any pain as a serialized array of bytes and then deserialize it in the other side.
 
Aram Azhari

GeneralRe: What are the reasons to SerializememberJason Newland13 Oct '11 - 23:28 
Problem with that, it will only de-serialize within the executable that serialized it. You can't take the serialized file and try to de-serialize it with another program.
GeneralRe: What are the reasons to SerializememberAram Azhari14 Oct '11 - 0:48 
Here's what you need to do:
1- Create another project for a class library.
2- Copy your class definition inside that project.
3- Add that project   (or the compiled DLL) to your existing projects as a reference.
 
This way you can have the same definition and you can deserialize without any problems.
 
Aram Azhari
GeneralSerializing image datamembersohst9 Sep '08 - 4:33 
Hi,
when serializing the image data out of a certain field of a dataset row, I don't get any error while performing the code, but then the image cannot be displayed by some reason. Do I have to peform anything additional to get those kind of data displayable?
 
Regards, Wolfgang
GeneralSerializing Lists/Arrays/etc.memberThanks for all the fish13 Aug '07 - 13:28 
easier than you think. they key/value system doesn't break down. your array variable is a named too, right? just use that, as if it were a primitive type
 

[Serializable()]
class idiot
{
  UInt32 id;
  List< string > blah;
 
  public idiot(SerializationInfo info, StreamingContext ctxt)
  {
    this.id = info.GetUInt32("id");
    this.blah = (List< string > )info.GetValue("blah", typeof(List< string > ));
  }
 
  public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
  {
    info.AddValue("id", this.id);
    info.AddValue("blah", this.blah);
  }
}

GeneralArrayList in my objectmemberSpyder_Snyper6 Aug '07 - 6:13 
So I'm trying to serialize my object, which contains a couple of arraylists.
 
What would be the best way to go about serializing those? I can't see the name-value pairs being the solution (although, I HAVE been wrong before...).
 
Thanks.
GeneralSerialize a complex classmemberNigel Bogle13 Apr '07 - 1:18 
I thought your article was generally very good but the class you use in your example is very simple. I presume this was so that the principle point of your example wouldn't be lost. I have a class that contains properties, ArrayLists and DataTables
 
Simply put, is there a way I can serialize / deserialize using the same principals used in your example.
 
Sniff | :^)
QuestionDoes this work with XMLSerialization?membervoodoo90558 Mar '07 - 9:16 
I haven't tried the example presented, but I have tried this using XMLSerialization and it doesn't look like the GetObjectData method is getting called. Does this work with the XMLSerializer?
QuestionCan I Serialize a InterfacememberIvelinaDoycheva26 Nov '06 - 22:21 
Confused | :confused:
AnswerRe: Can I Serialize a InterfacememberTim Wiffen7 Mar '07 - 2:48 
Of course not.
 
An interface is just a contract that objects adhere to. There is no data to serialize.
 
You can serialize an object that implements an interface as long as that object has been marked as serializable. In fact, you don't need to know what the type of the object is as long as you know it is serializable.
 
Tim
 
Gi Diet Guide

GeneralXMLSerializationmemberBVandenbon25 Oct '06 - 1:13 
I have used Serialization several times and it can not be denied that it is very useful for communication.
 
In Java I used to use Serialization to save data to files, because it was easy and clean coding. In .NET there's such a thing like XMLSerialization now! I think most people will now prefer XMLSerialization to save their files.
 
BramGo
---
Watch the progress of my realtime strategy game at http://antwars.blogspot.com
---
QuestionShould implement the interface ISerializable?memberanees7728 Jun '06 - 23:40 
Hi Kamal,
 
I have a doubt. Should we implement the ISerializable interface to do object serialization?
 

 
Thanks
Anees
AnswerRe: Should implement the interface ISerializable?memberGanesh Paulraj6 Oct '06 - 3:12 
ISerializable contain single method void GetObjectData(SerializationInfo info, StreamingContext context), which is implemented in the example.
AnswerRe: Should implement the interface ISerializable?membertallgill27 Jun '07 - 5:20 
To serialize an object, you need to either mark the object class with the [Serializable] attribute or implement the ISerializable interface. This example is doing both. But you can get away by just marking it as [Serializable] too.
 
Sukh Gill
Generalsimple yet consisememberDarchangel6 Apr '06 - 6:40 
I think my subject sums up my thoughts on your article. Very nice. Definitely got a 5 from me. Keep up the good work!
 
=========================
"Documentation is like sex: when it is good, it is very, very good; and when it is bad, it is better than nothing."
- Dick Brandon
GeneralSerializing/ Deserializing an ArrayListmemberMax Leifer7 Oct '05 - 6:58 
MessageSettings - my custom class
Strategy - ArrayList of MessageSettings
 

Saving (Serializing) an ArrayList.
 
MessageSettings [] tempArray =
(MessageSettings[]) Strategy.ToArray( typeof(MessageSettings) );
XmlSerializer s = new XmlSerializer( typeof(MessageSettings[]) );
TextWriter w = new StreamWriter( fileSaveStrategy );
s.Serialize( w, tempArray );
w.Close();
 

 
Loading (Deserializing) an ArrayList
 
XmlSerializer s = new XmlSerializer( typeof(MessageSettings[]) );
TextReader r = new StreamReader( fileLoadStrategy );
MessageSettings [] tempArray =
(MessageSettings[]) s.Deserialize( r );
r.Close();
Strategy.Clear();
Strategy.AddRange(tempArray);
 

-- modified at 12:58 Friday 7th October, 2005
GeneralVery... very good.memberCaio Proiete9 Jun '05 - 5:02 
Just what I was looking for... I was having some troubles to serialize the state of one webcontrol to viewstate, and you just solved it. Got my five.
 
cheers,
 
Caio Proiete WTF | :WTF:
MCT, MCSD, MCDBA, MCAD .NET, MCSD .NET
GeneralGetting a class to deserialize itselfmembermichaelfomin3 Apr '05 - 18:03 
Hey there,
 
I am aware of how to deserialize in C#...
 
void Class::Deserialize()
{
Stream stream = File.Open("Data.data", FileMode.Open);
BinaryFormatter bformatter = new BinaryFormatter();
MyClass myClass = (MyClass )bformatter.Deserialize(stream);
}
 
The above code creates a new MyClass object and sets its parameters from "Data.dat"
 
However, I would like to deserialize from within MyClass. So that I can call...
 
void Class::Deserialize()
{
MyClass myClass = new MyClass;
myClass.Load("Data.Dat");
}
 
Ideally, the Load function would do something like this, however this code is not allowed.
 
void MyClass::Load(string filePath)
{
Stream stream = File.Open(filePath,FileMode.Open);
BinaryFormatter bformatter = new BinaryFormatter();
this = (MyClass )bformatter.Deserialize(stream);
}
 
Any advide would be great.
GeneralRe: Getting a class to deserialize itselfmemberBVandenbon25 Oct '06 - 1:38 
Very often in other existing classes of the .NET framework you will find that this is implemented as a static function.
 
Some examples:
Image Image.FromFile(string path);
Image Bitmap.FromFile(string path);
FileStream File.OpenText(string path);
 
What you are trying with the "this=" is impossible in .NET. If you just put it in a static function you can use the following code
 
public static MyClass FromFile(string filePath)
{
Stream stream = File.Open(filePath,FileMode.Open);
BinaryFormatter bformatter = new BinaryFormatter();
return (MyClass )bformatter.Deserialize(stream);
}
 
If you implement this static function within the SAME class (like with the Image example I gave earlier) you will still be able to access all private variables of instances of that class as well, example.
 
public static Person FromFile(string filePath)
{
Stream stream = File.Open(filePath,FileMode.Open);
BinaryFormatter bformatter = new BinaryFormatter();
Person p = (Person)bformatter.Deserialize(stream);
 
p.defaultFilePath = filePath;
//that would allow you to write a SaveOnDefaultPath() function
 
p.strFirstName = "Bram";
p.otherVariables = somevalue;
}
 
I usually implement it that way and also code remains pretty clean like:
MyClass instance = MyClass.FromFile("blablabla.dat");
 
In fact, I believe it is cleaner than this way:
MyClass instance = new MyClass();
instance.Load("blablabla.dat");
 
I hope this was useful Wink | ;)
I have to go Smile | :) going to be late again
 
BramGo
---
Watch the progress of my real time strategy game at http://antwars.blogspot.com
---
Generalserializable/deserializable from DLL to Windows applicationsussAnonymous13 Mar '05 - 21:58 
Hi , i want to pass a serializable object from .NET DLL to .NET Windows application.
My question is can call for the deserializable object function , without having the class object definition on the Windows application side.
 
Thanks
asaf
GeneralSerializing a simple arraymemberLe_MuLoT11 Mar '05 - 8:58 
Hi,
I would like to serialize a simple 2D array like this :
int[,] MyArray;
 
But when I try :
info.GetValue("MyArray",typeof(int[,]));
 
I've got this error : managed EE does not understand expression's syntax.
Cry | :((
 

So thanks for your help ! Big Grin | :-D
 
- Le_MuLoT

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 1 Feb 2002
Article Copyright 2002 by omkamal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid