Sunday, June 26, 2005

Cache XML Dataset

Here is a quick way to retrieve configuration data from an XML files (not web.config) in ASP.NET. This supports caching and is quick and efficient.
public static DataRow LoadXML(string XMLFileName)
{
DataSet ds1;

if (HttpContext.Current.Cache[XMLFileName] == null)
{ //not in cache so we create it
ds1 = new DataSet();
ds1.ReadXml(XMLFileName);//read it
HttpContext.Current.Cache.Insert(XMLFileName, ds1,
new CacheDependency(XMLFileName));//save it
}
else //or load it from cache
{
ds1=(DataSet) HttpContext.Current.Cache[XMLFileName];
}

DataRow r=ds1.Tables[0].Rows[0];
return r;
}
Every time you need a data from a simple config file, you can get the data out like this below without any consequences. There is a Cache dependency on the file so if it changed, the cache is updated. The key is set to the filename

datarow r = LoadXML(@"c:\\file.xml");
string foo=r["blahColumn"];
.