How do you work with SessionStateItemCollection in C# (ASP.net)
-
22-07-2019 - |
Question
If I store the contents of an xml file (name -> value) in a session collection, whats the best way of accessing it on another page (i.e not the one that the below script runs on).
Is it just a job of creating a new instance of SessionStateItemCollection on each page I want to access the collection?
System.Xml.XmlDocument oXmlDoc = new System.Xml.XmlDocument();
oXmlDoc.Load(Server.MapPath("xml.xml")); //load XML file
XmlNode root = oXmlDoc.DocumentElement;
SessionStateItemCollection PSess = new SessionStateItemCollection(); //session collection
for (int x = 0; x < root.ChildNodes.Count; x++) //loop through children and add to session
{
PSess[root.ChildNodes.Item(x).Name] = root.ChildNodes.Item(x).InnerText; //add xml values to session
}
Solution
If this is in ASP.NET then I don't see why you would create a new SessionStateItemCollection object. In this case as you would need to handle persisting this between pages yourself.
ASP.NET provides access to a SessionStateItemCollection object via the Session object of the Page or the HttpContext.Current object if you are wnating to use this from a class. You can store your key values pairs in there via the Session object and retrieve them from the Session object on subsequent pages.
I would rewrite your code as follows
System.Xml.XmlDocument oXmlDoc = new System.Xml.XmlDocument();
oXmlDoc.Load(Server.MapPath("xml.xml")); //load XML file
XmlNode root = oXmlDoc.DocumentElement;
for (int x = 0; x < root.ChildNodes.Count; x++) //loop through children and add to session
{
Session[root.ChildNodes.Item(x).Name] = root.ChildNodes.Item(x).InnerText; //add xml values to session
}
You can now access the contents from another page using the Session object (the following code will interate through everything store in the session):
for (int i = 0; i < Session.Count; i++)
{
Response.Write(Session.Keys[i] + "-" + Session[i].ToString());
}