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:
VB:
Public Class MyClass
    Public field1 As String
    Public field2 As Integer
    Public field3 As OtherType

    Sub doSomething()

    End Sub
End Class
C#:
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:
VB:
Imports System.Xml.Serialization
Imports System.IO
C#:
using System.Xml.Serialization;
using System.IO;
Then, declare that your class can be serialized by editing the class declaration:
VB:
<Serializable()> Public Class MyClass
C#:
[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:
VB:
    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)
        sr.Close()
        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)
        sw.Close()
    End Sub
C#:
public static MyClass load(string f)
{
 XmlSerializer xs = new XmlSerializer(typeof(MyClass));
 StreamReader sr = new StreamReader(f);
 MyClass data = (MyClass)xs.Deserialize(sr);
 sr.Close();
 return data;
}

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

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):
MyClassInstance.save("path")
Save (C#):
MyClass MyClassInstance = MyClass.load("path\\to\\file.xml");

Conclusion

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