views:

340

answers:

2

Is it possible to get the expiry datetime of an HttpRuntime.Cache object? If so, what would be the best approach?

+2  A: 

Cache by itself doesn't expire. Either it can have items (which expire) or not have any items at all.

shahkalpesh
+3  A: 

I just went through the System.Web.Caching.Cache in reflector. It seems like everything that involves the expiry date is marked as internal. The only place i found public access to it, was through the Cache.Add and Cache.Insert methods.

So it looks like you are out of luck, unless you want to go through reflection, which I wouldn't recommend unless you really really need that date.

But if you wish to do it anyway, then here is some code that would do the trick:

private DateTime GetCacheUtcExpiryDateTime(string cacheKey)
{
 object cacheEntry = Cache.GetType().GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Cache, new object[] { cacheKey, 1 });
 PropertyInfo utcExpiresProperty = cacheEntry.GetType().GetProperty("UtcExpires", BindingFlags.NonPublic | BindingFlags.Instance);
 DateTime utcExpiresValue = (DateTime)utcExpiresProperty.GetValue(cacheEntry, null);

 return utcExpiresValue;
}
Tom Jelen