How to Clear ASP.NET Web Cache

March 28, 2008

In ASP.NET you can remove an item from the web cache by invoking Cache.Remove(string ID). But, what happens when, for some reason, you want to quickly clear the whole cache? There's no Clear or RemoveAll method in System.Web.Caching.Cache object.

WORKAROUND

You can iterate over all the entries and remove them by their key (or ID), using the GetEnumerator method of the Cache class.

IDictionaryEnumerator enumerator \= Cache.GetEnumerator();  
  
while(enumerator.MoveNext())  
{  
Cache.Remove(enumerator.Key);  
}

Profile picture

Written by Edin Kapić Insatiably curious code-writing tinkerer. Geek father. Aviation enthusiast. Cuisine journeyman. Follow me on Twitter