Click here to Skip to main content
15,868,164 members
Articles / Programming Languages / C#
Article

How to Serialize a TreeNode Object

Rate me:
Please Sign up or sign in to vote.
2.60/5 (17 votes)
20 Mar 2008CPOL3 min read 66.8K   13   26
To serialize a TreeNode derived class is not easy, but it can be done

Introduction

As serializing of a TreeNode object does not work as it is said in the Microsoft’s online page, or other Web pages, e.g. Object Serialization using C# on this Web site.

If you try to write a class inherited from a TreeNode object, you will find a NullPointerException during serialization to/from the file. Your process crashes, and a wonderful and beautiful NullPointerException is shown (if you've not caught it).

The reason is one, simple and not easy to reach: the TreeNode object implements the ISerializable interface but deserialization does not work very well, that's because you cannot simply serialize an object that inherits the TreeNode and be able to [Serialize] it.

You can find an example of the problem here. I did not write that code, but it's a great example, and in this article you can find how to resolve it.

So, if you try to write code like this:

C#
[Serializable]
public class MyObject : TreeNode
{
public MyObject(string dirName) : base(dirName)
{
}

You will find that, one of the most simple code ever made will crash when you try to serialize and de-serialize the MyObject object.

C#
static void Main(string[] args)
{
MyObject obj = new MyObject("blabla");
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
}

Don't worry, there is a SIMPLE and EASY solution, but it would be easier if [Serialize] tag worked as it was supposed to (like Java). I think it's not necessarily a full project to show how it can be done, it's really very simple!

Background

I surfed the Internet, spending a lot of hours trying to find the answer for this problem in C#. Don’t worry, it does not exist anywhere but here. I found some objects that used TreeNode and TreeView as a base class, and derived it (and you had to derive that derived class, not very practical). I suggest that you inherit the TreeNode class, because the TreeView class is used only for GUI approaches (I must say it: use the Facade pattern, very easy and useful while using a memory-GUI duet).

But it was not what I wanted, and it was a lot of work to change my project, and mapping all my work to store it in an XML (so cool, so fantastic, …) but I wanted binary files.

What I wanted was to derive a TreeNode, and store it to a binary or XML file, does not matter what the structure of my object was. At Microsoft's Web page was no answer, I tried to find it. And I won.

Using the Code

After a long time, I found the answer: you can derive your class from TreeNode, but the serializing way works different from other classes (not to say Microsoft’s help). This is how I did it:

First of all, derive your class:

C#
[Serializable]
public class DbVisioFile: TreeNode, …
{
    ///THIS IS WHAT I WANT TO STORE IN BINARY OR XML FILES
    private string mFilePath;
    private string mOwner;
    private string mSummary;
    private string mDifferences;
    private string mComments;
    private Version mVersion;

After this, make your own Serialization control-code:

C#
#region Serialization control
protected DbVisioFile(SerializationInfo si, StreamingContext context)
: base(si, context)
{
    this.FilePath = si.GetString("FilePath");
    this.Owner = si.GetString("Owner");
    this.Summary = si.GetString("Summary");
    this.Differences = si.GetString("Differences");
    this.Comments = si.GetString("Comments");
    this.Version = new Version(si.GetString("Version"));
}

protected override void Serialize(SerializationInfo si, StreamingContext context)
{
    base.Serialize(si, context);
    si.AddValue("FilePath", this.FilePath);
    si.AddValue("Owner", this.Owner);
    si.AddValue("Summary", this.Summary);
    si.AddValue("Differences", this.Differences);
    si.AddValue("Comments", this.Comments);
    si.AddValue("Version", this.Version.ToString());
}
#endregion

You can see that the code has no reason to work, but it does. It is a mixture of the ISerializable and [Serializable] point of view.

Points of Interest

In the overriding of the Serialize method, the first line is:

C#
base.Serialize(si, context);

As a result of this, the treenode structure is serialized to disk.

You have to be very careful with calling the following line in the constructor code.

C#
:base(si, context) 

If It Was Useful To You...

... or if you have any questions, please send me an email at victoragus@yahoo.es with a clear question and the source code.

Remember, the beginnings are very hard. And if you work with a language that doesn't work as it is supposed to, it is even harder.

Sorry for my English

So sorry for my English, but if you are English, try to rewrite it in Spanish and send me. We both will have some laughs!

History

  • 20th March, 2008: Initial post

License

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


Written By
Instructor / Trainer
Spain Spain
Young and handsome code-writer, born and living in Spain, left the SW developer job to a very wonderful life of teaching other how to waste your life in front of a 20" machine.
I don't like to write code for other, but code & programs that I write for me, that's great!

Comments and Discussions

 
Questionthanks you very much Pin
superjugy10-Aug-11 7:41
superjugy10-Aug-11 7:41 
AnswerRe: thanks you very much Pin
Victor_Gus17-Sep-11 14:59
Victor_Gus17-Sep-11 14:59 
GeneralMy note is 5 + XML serialization question Pin
yuriyag2-Feb-11 23:07
yuriyag2-Feb-11 23:07 
GeneralRe: My note is 5 + XML serialization question Pin
yuriyag3-Feb-11 3:16
yuriyag3-Feb-11 3:16 
GeneralRe: My note is 5 + XML serialization question Pin
yuriyag3-Feb-11 3:31
yuriyag3-Feb-11 3:31 
AnswerFinally I have found a good idea right here, on codeproject! Pin
yuriyag3-Feb-11 6:49
yuriyag3-Feb-11 6:49 
GeneralRe: Finally I have found a good idea right here, on codeproject! Pin
Victor_Gus1-Aug-11 5:07
Victor_Gus1-Aug-11 5:07 
GeneralExcellent Article, thank you Pin
dvanderwerken24-Sep-09 10:03
dvanderwerken24-Sep-09 10:03 
GeneralMany Thanks Pin
kal7hos31-May-09 12:29
kal7hos31-May-09 12:29 
GeneralRe: Many Thanks Pin
Victor_Gus17-Sep-11 14:51
Victor_Gus17-Sep-11 14:51 
GeneralOK, that's better Pin
PIEBALDconsult22-Mar-08 6:40
mvePIEBALDconsult22-Mar-08 6:40 
GeneralRe: OK, that's better Pin
Victor_Gus22-Mar-08 13:46
Victor_Gus22-Mar-08 13:46 
GeneralRe: OK, that's better Pin
PIEBALDconsult22-Mar-08 15:57
mvePIEBALDconsult22-Mar-08 15:57 
AnswerRe: OK, that's better Pin
Victor_Gus23-Mar-08 1:44
Victor_Gus23-Mar-08 1:44 
GeneralRe: OK, that's better Pin
PIEBALDconsult23-Mar-08 4:53
mvePIEBALDconsult23-Mar-08 4:53 
GeneralRe: OK, that's better Pin
Victor_Gus23-Mar-08 11:18
Victor_Gus23-Mar-08 11:18 
Generalif [Serialize] tag worked as supposed to (like Java). Pin
Derek Bartram21-Mar-08 15:47
Derek Bartram21-Mar-08 15:47 
GeneralRe: if [Serialize] tag worked as supposed to (like Java). Pin
Victor_Gus22-Mar-08 5:59
Victor_Gus22-Mar-08 5:59 
GeneralRe: if [Serialize] tag worked as supposed to (like Java). Pin
Derek Bartram22-Mar-08 6:37
Derek Bartram22-Mar-08 6:37 
GeneralRe: if [Serialize] tag worked as supposed to (like Java). Pin
Victor_Gus1-Aug-11 5:08
Victor_Gus1-Aug-11 5:08 
GeneralPlease explain Pin
PIEBALDconsult21-Mar-08 4:43
mvePIEBALDconsult21-Mar-08 4:43 
GeneralRe: Please explain Pin
Victor_Gus22-Mar-08 5:58
Victor_Gus22-Mar-08 5:58 
Ok, I'll modify the introduction. It's a very hard problem, it drove me crazy for a lot of time, due to Framework does not work as supposed.

Java expert, .NET beginner Frown | :(

GeneralSomething I have never seen... Pin
Justin Perez20-Mar-08 3:18
Justin Perez20-Mar-08 3:18 
JokeRe: Something I have never seen... Pin
Victor_Gus20-Mar-08 3:36
Victor_Gus20-Mar-08 3:36 
GeneralRe: Something I have never seen... Pin
Justin Perez20-Mar-08 3:37
Justin Perez20-Mar-08 3:37 

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.