Posts Tagged ‘Session’

Xml Serializable Session (Dictionary)

January 8, 2009

In my recent (c#) project, I need save something in a session (or dictionary) and I need save the session into a standard xml document.

XmlSession session = new XmlSession();

session["string"] = "I'm a string";

session["number"] = 42;

// Any object. Make sure it can be serialize to a standard xml document.
session["object"] = new MyObject("obj", 100, DateTime.Now);

using (Stream stream = File.Create("session.xml"))

using (Stream stream = File.OpenRead("session.xml"))
session = XmlSession.Deserialize(stream);

// "I'm a string"
string s = (string)session["string"];

// 42
int num = (int)session["number"];

MyObject o = (MyObject)session["object"];

If you have encountered the same requirement, you would know that is not a easy work.

You can use the XmlSerializer to do this object-xml mapping, but you need to know all the types of value in your session, especially when you deserialize the xml document.

OK, OK. I did all these for you.

Just download and session it.