Monday, September 30, 2013

[For .NET beginners] How to save (serialize) an instance of an object

When I began to learn Visual Basic .NET (that is when I started programming, because it's the first language I studied), after I have understood the Object-Oriented paradigm, I asked mysellf the question: "How can I save an object to a file?", and, after some Google searches, I found that the answer is named Serialization. In this post I will try to make a basic explanation of the XML serialization, hoping it will be useful for people that are learning a .NET language (VB or C#) and is asking the same question.

Why XML?

eXtensible Markup Language is not the only serialization format that can be used in .NET, but as can be read from discussions like this, it's the best, because XML files are human-readable, and files generated from your program can be read in other programs (and vice versa).

Make your .NET object XML-serializable

First of all, edit your class to make it serializable; before starting, it will probably be something like this:
Public Class MyClass
    Public field1 As String
    Public field2 As Integer
    Public field3 As OtherType

    Sub doSomething()

    End Sub
End Class
public class MyClass
 public string field1;
 public int field2;
 public OtherType field3;

 public void doSomething()

First of all, you have to include the necessary namespaces; add at the beginning of your file:
Imports System.Xml.Serialization
Imports System.IO
using System.Xml.Serialization;
using System.IO;
Then, declare that your class can be serialized by editing the class declaration:
<Serializable()> Public Class MyClass
[Serializable()] public class addonManifest
Now, the most important part: let's add into the class the methods to load and save the object from and to a file:
    Public Shared Function load(ByVal f As String) As MyClass
        Dim xs As New XmlSerializer(GetType(MyClass))
        Dim sr As New StreamReader(f)
        Dim data As MyClass = CType(xs.Deserialize(sr), MyClass)
        Return data
    End Function

    Public Sub save(ByVal f As String)
        Dim xs As New XmlSerializer(GetType(MyClass))
        Dim sw As New StreamWriter(f)
        xs.Serialize(sw, Me)
    End Sub
public static MyClass load(string f)
 XmlSerializer xs = new XmlSerializer(typeof(MyClass));
 StreamReader sr = new StreamReader(f);
 MyClass data = (MyClass)xs.Deserialize(sr);
 return data;

public void save(string f)
 XmlSerializer xs = new XmlSerializer(typeof(MyClass));
 StreamWriter sw = new StreamWriter(f);
 xs.Serialize(sw, this);

Call the save/load methods

Now instances of your class can be loaded and saved from and to XML files by simply calling the save and load methods we've just written, passing as a parameter the file's path:
Load (VB):
Dim MyClassInstance As MyClass = MyClass.load("path\to\file.xml")
Load (C#):
MyClass MyClassInstance = MyClass.load("path\\to\\file.xml");
Save (VB):"path")
Save (C#):
MyClass MyClassInstance = MyClass.load("path\\to\\file.xml");


If you have some problems implementing this, leave a comment, I'll try to improve the article.
See you at the next post!

No comments:

Post a Comment