How to add a System.Xml.XmlDocument type to applications state
I am using Asp.net 3.5 and C#
I have to add an XmlDocument to my application state so that everytime my application doesnt access the XML file on my filesystem, I will add this at the Application_Start() function in Global.asax.cs
I am adding this to system state as :
protected void Application_Start(Object sender, EventArgs e)
{
string filePath = Server.MapPath("<path to my XML FILE>");
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlTickerDoc.Load(filePath);
}
finally
{
HttpContext.Current.Application["xmlDoc"] = xmlDoc;
}
}
In this code i try to load the xml file and if the file is not loaded due to any problem then i am wanting a null XmlDocument.
I access this XmlDocument as :
XmlDocument xmlDoc = new XmlDocument();
xmlDoc = HttpContext.Current.Application["xmlDoc"];
the 开发者_运维百科error i get while build is
Cannot implicitly convert type 'object' to 'System.Xml.XmlDocument'. An explicit conversion exists
So How to assign the HttpContext.Current.Application["xmlDoc"] variable as System.Xml.XmlDocument ?
Your problem is here:
xmlDoc = HttpContext.Current.Application["xmlDoc"];
Try
xmlDoc = HttpContext.Current.Application["xmlDoc"] as System.Xml.XmlDocument;
Got the answer after a little googling, a simple one but can be tricky for a PHP developer working on C# (as it was in my case) well i just had to explicitly cast my application state variable to XmlDocument that is at place of :
XmlDocument xmlDoc = new XmlDocument();
xmlDoc = HttpContext.Current.Application["xmlDoc"];
I used :
XmlDocument xmlDoc = new XmlDocument();
xmlDoc = (XmlDocument) HttpContext.Current.Application["xmlDoc"];
and it becomes Robust :)
can any one tell me what will be the lifetime of this ApplicationState Variable ?
精彩评论