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"))
{
session.Serialize(stream);
}
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.
Tags: c#, Dictionary, Session, Xml Serializable
August 14, 2009 at 11:20 am |
Nice, but only the last session item ( session["object"] in the example ) appears to be saved in the xml file.
August 14, 2009 at 3:35 pm |
one bug. fixed.
August 17, 2009 at 8:22 am |
It works – thanks.