Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  Data Programming  »  XML  »  Serialization in .NET
Serialization in .NET
by Mark Butenko | Published  01/07/2004 | XML | Rating:
Mark Butenko

Marc Butenko is a Computer Systems Analyst for the Montana Department of Transportation, and writes applications for various engineering groups using Visual Basic .NET. He has a B.S. in Mechanical Engineering and a M.S. in Computer Science.

Marc's Visual Basic experience covers everything from VB4 (16-bit) to Visual Basic .NET and he enjoys beta testing software for major software companies. He says that it's always nice to find someone else's bugs and let them fix them, and gives him a great opportunity to get experience with a wide variety of software.

You can reach Mark at mbutenko@bresnan.net

 

View all articles by Mark Butenko...
Serialization in .NET

Article source code: dotnet_serialization.zip

Introduction

When developing smaller applications that do not have a database (or other formal storage mechanism) or data that doesn't need to be stored in a database (such as the state of a web application), you often still would like to save the data for later retrieval. There are many ways to do this, but many of them are subject to a lot of extra code (work) and extra time spent debugging. With .NET, there is now an easy way to add this functionality to your code with only a few lines of easily tested code. This easy way is called serialization.

Serialization is the process of storing an object, including all of its public and private fields, to a stream. Deserialization is the opposite – restoring an object's field values from a stream. The stream is generally in the form of a FileStream, but does not have to be. It could be a memory stream or any other object that is of type IO.Stream. The format can be anything from XML to binary to SOAP.

In this article, I will show the storage and retrieval of an object's state using both XML serialization and binary serialization. The others are very similar and simply require the use of a different serialization class.

The Basics

The basics of serialization are simple. You have to enable serialization for the object you want to serialize, create a serialization object to write the file and create a deserialization object to read the file.

This simple example uses two classes to make up the object type that we are going to serialize. Our classes for this example are:

<SERIALIZABLE< font>()> _
Public Class Employee
    Public Name As String
    Public ID As Integer
    <NONSERIALIZED< font>(), Serialization.XmlIgnore()> Public Salary As Single
    Public Position As String
End Class

<SERIALIZABLE< font>()> _
Public Class Employees
    Public Sub New()
    End Sub

    Public Sub New(ByVal NumberOfEmployees As Integer)
        ReDim Workers(NumberOfEmployees - 1)

        For i As Integer = 0 To NumberOfEmployees - 1
            Workers(i= New Employee
        Next
    End Sub

    Public Workers() As Employee
End Class

Note the use of the "Serializable" attribute. This tells the serialization object that these structures are allowed to be serialized. The "Serializable" attribute is not required when using XML serialization, but it is still a good idea to designate it.

We can also prevent a field from being serialized. This is useful when the field value has no specific meaning except in this instance of the application. The designation of a field with the "NonSerialized" (for binary serialization) or "Serialization.XMLIgnore" (for XML serialization) will prevent a field from being serialized. Since we are doing both binary and XML serialization, we have to apply both attributes.

Serializing our Object

To perform the serialization of our object only takes a few lines of code. We first must create a serializing object. In our case, this is an object created from the Serialization.XMLSerializer or BinaryFormatter class. We also create a stream (of type FileStream) in which to store the object. Then we call the Serialize method or our serializing object to do the work, then we close the stream.

The code looks like this:

'XML Serialization
Dim Serializer As New Serialization.XmlSerializer(GetType(Employees))
Dim DataFile As New FileStream("Sample.dat"FileMode.Create_
    FileAccess.WriteFileShare.None)

Serializer.Serialize(DataFileData)
DataFile.Close()
Data = Nothing

'Binary Serialization
Dim Serializer As New BinaryFormatter
Dim DataFile As New FileStream("Sample.bin"FileMode.Create_
    FileAccess.WriteFileShare.None)

Serializer.Serialize(DataFileData)
DataFile.Close()
Data = Nothing

The last line in both cases is merely to empty the instance of our data class to demonstrate that when we deserialize the stream into our object we are actually getting data from the file and not from something remaining in memory.

Notice also the inclusion of the following Imports statements at the top of the form:

Imports System.Xml
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization

Deserializing

To deserialize, the code is almost identical as the serialization code except we call the Deserialize method or the serialization object:

'XML Deserialization
Dim Deserializer As New Serialization.XmlSerializer(GetType(Employees))
Dim DataFile As New FileStream("Sample.dat"FileMode.Open_
    FileAccess.ReadFileShare.None)

Data = CType(Deserializer.Deserialize(DataFile), Employees)
DataFile.Close()

'Binary Deserialization
Dim Deserializer As New BinaryFormatter
Dim DataFile As New FileStream("Sample.bin"FileMode.Open_
    FileAccess.ReadFileShare.None)

Data = CType(Deserializer.Deserialize(DataFile), Employees)
DataFile.Close()

Running The Sample Solution

Now that we have reviewed how it is done, take a look at it in action.

Run the sample code and press the "Show Object Data" button. It will show the current contents of the Employees object that is loaded as part of the Form_Load event.

Now serialize the object using the "Serialize to XML" or "Serialize to Binary" buttons. Press the "Show Object Data" button and it will tell us the object is empty.

If we deserialize the stream, and press the "Show Object Data" button again we can see we have our data back. When running these examples, take note of the salary value. Since we designated this field to not be serialized, it is zero after deserializing.

Also, take a look at the two output files ("Sample.xml" and "Sample.bin"). These files could be used by other applications or reused by our application. The XML file, shown here, could easily be used by other applications or used to create an HTML page by applying an XSL style sheet:

<?xml version="1.0"?>
<EMPLOYEES xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <WORKERS>
    <EMPLOYEE>
      <NAME>Marc Butenko</NAME>
      <ID>1</ID>
      <POSITION>Computer Systems Analyst</POSITION>
    </EMPLOYEE>
    <EMPLOYEE>
      <NAME>Bill Gates</NAME>
      <ID>0</ID>
      <POSITION>CEO</POSITION>
    </EMPLOYEE>
    <EMPLOYEE>
      <NAME>John Doe</NAME>
      <ID>2</ID>
      <POSITION>Janitor</POSITION>
    </EMPLOYEE>
  </WORKERS>
</EMPLOYEES>

Summary

Other uses of the serialization object are also available. If we had chosen to serialize the object to a memory stream, we could then write the data to an encrypted file stream to prevent the data from being viewed by prying eyes.

Now that we have covered the basics of serialization, try experimenting with it using different serialization classes and attributes. I often use it in simple applications to provide a quick and easy data storage solution. Hopefully you have found this educational and enlightening and can make use of the material here in your applications.

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:4.48979591836734 out of 5
 49 people have rated this page
Article Score23168
Related Articles
Comments    Submit Comment

Comment #1  (Posted by Deepa Kamath on 01/16/2004)

hi,

I am writing a custom form designer. I need to know how to implement serialization for the cut,copy,paste,undo,redo features for the controls.

Please let me know
Thank You
Deepa
 
Comment #2  (Posted by Marc Butenko on 01/16/2004)

I don't think that you need to use serialization to do cut, paste, etc.

To do this, you will need to use the Clipboard class and do something like the following:

To set the object on the clipboard:
Clipboard.SetDataObject(ControlObject)


To retrieve it:
Dim iData as IDataObject = Clipboard.GetDataObject()
Dim Ctrl as ControlObjectType

Ctrl = CType(iData.GetData(ControlObjectType), ControlObjectType)

Hope that helps,
Marc
 
Comment #3  (Posted by an unknown user on 01/30/2004)

I believe the clipboard uses serialization under the covers to store the object.

 
Comment #4  (Posted by 2lits on 04/28/2004)

Hi Marc!

Great article. I have some questions regarding Serialization. Why is that I encounterd an error if my property type is a user define type..

Example

Class DateTimeProperty
Private mDate as Date
Public Sub New(value as Date) as Date
mDate = value
End Sub
End Class

Class InheritDatetimeProperty
Dim mDate as DateTimeProperty
Public Property NewDate() as DateTimeProperty
get
return mDate
end get
set (byval value as DateTimeProperty)
mDate = value
end set
End Property

End Class

 
Comment #5  (Posted by element[0] on 05/22/2004)

Good article, i found the code examples very concise and exactly what was needed. It took a surprising amount of googling to actually find an article which actually had some useful examples.

keep up the good work
 
Comment #6  (Posted by kishore on 07/29/2004)

hi,

I am writing a custom form designer. I need to know how to implement cut,copy,paste,undo,redo features for the controls.

Please let me know
Thank You
kishore
 
Comment #7  (Posted by amarjeet on 08/11/2004)

I am student and doing project synchronisinf inforametion database using xml and web services . databse is sqlbase. can u pls help in connectivity between vb.net and sqlbase using ado.net

 
Comment #8  (Posted by Marc Butenko on 08/13/2004)

This is really beyond the scope of the article, but look at using
SQLDataAdapters and SQLDataClients.

 
Comment #9  (Posted by Fred on 10/18/2004)

Hi Marc. Excuse my ignorance, but why does your example define the variable "Public Workers() As Employee" but not instatiate an object while the 'parent' class is instatiated thus "Dim Data as New Employees(3)?

 
Comment #10  (Posted by Marc Butenko on 10/18/2004)

Fred,

The "Dim Data as New Employees(3)" is using the constructor that defines how many "Workers" to have in the Data (e.g., Employees) object.
 
Comment #11  (Posted by an unknown user on 01/19/2005)
Rating
To the point with a live example.
 
Comment #12  (Posted by an unknown user on 04/14/2005)
Rating
I was looking for c# code and this looks like vb code.
 
Comment #13  (Posted by an unknown user on 04/19/2005)
Rating
It doesn't give any real world scenario
 
Comment #14  (Posted by an unknown user on 04/19/2005)
Rating
Nice starting point for serialization.
 
Comment #15  (Posted by enrique on 04/20/2005)

a question if you may... will this data still be retrieved even i turn off the computer??
 
Comment #16  (Posted by Marc Butenko on 04/21/2005)

Yes, the data will be saved in the file specified and will be available even if the computer is turned off or restarted.
 
Comment #17  (Posted by an unknown user on 04/23/2005)
Rating
Mark, that's a cool article and helped me on the way. Thanks a lot.

"I was looking for c# code and this looks like vb code." Hey man, it is VB code. If you're not sure about it yet, I don't think you should be messing with programming at all. But why did you rate it so low? Because it wasn't what you were looking for? Get real, man! And when I hear comments like "It doesn't give any real world scenario", I get the creeps. What do you guys want? A complete real-world program?
 
Comment #18  (Posted by an unknown user on 04/27/2005)
Rating
An excellent article! It explains the topic clearly and the examples are easy to follow.
 
Comment #19  (Posted by an unknown user on 05/02/2005)
Rating
Good article. Concise and easy to understand.
 
Comment #20  (Posted by an unknown user on 05/02/2005)
Rating
Good article. Concise and easy to understand.
 
Comment #21  (Posted by an unknown user on 05/07/2005)
Rating
Thouroughly enjoyed the article. Concise, to the point, without any mysterious jargon.
 
Comment #22  (Posted by an unknown user on 05/30/2005)
Rating
What's the point? It's the same crappy serialization example used everywhere but with some extra output forms.
 
Comment #23  (Posted by an unknown user on 06/07/2005)
Rating
Clear and very helpful. Thanks. - Didaskalos
 
Comment #24  (Posted by an unknown user on 08/25/2005)
Rating
Awesome. Thanks a lot man. Everybody's trying to explain serialization in the most complicated ways while you kept it elegant and simple. Maybe you should move the methods serialize and deserialize inside the class...
Di Vece
 
Comment #25  (Posted by suresh on 09/01/2005)
Rating
Very nice explanation
 
Comment #26  (Posted by an unknown user on 12/28/2005)
Rating
Information iknow already but examle is good C# version Will be appreciated.

 
Comment #27  (Posted by an unknown user on 04/25/2006)
Rating
it will be betten if u discribe clearly how to do it.
 
Comment #28  (Posted by an unknown user on 05/31/2006)
Rating
I think this is clear and concise code. Thank you for sharing! :)
 
Comment #29  (Posted by an unknown user on 07/11/2006)
Rating
Very good attempt to rightly drive the point
!
 
Comment #30  (Posted by an unknown user on 09/25/2006)
Rating