How to Clear all elements from Cache

There are many situations when we want to clear contents of the cache in our ASP. Net application. Here is a quick and dirty way to remove all the contents from our cache.

        /// <summary>

        /// Clears all the data from Cache

        /// </summary>

        public void ClearCache()

        {

            try

            {

                List<string> keyList = new List<string>();

                IDictionaryEnumerator CacheEnum = HttpContext.Current.Cache.GetEnumerator();

                string cacheKey;

 

                //Read all the keys from cache and store them in a list

                while (CacheEnum.MoveNext())

                {

                    cacheKey = CacheEnum.Key.ToString();

                    keyList.Add(cacheKey);

                }

 

                //Remove entries from cache

                foreach (string key in keyList)

                {

                    HttpContext.Current.Cache.Remove(key);

                }

                keyList.Clear();

                Response.Write("Cache Cleared");

            }

            catch

            {

                Response.Write("Cache NOT Cleared");

            }

        }


General I create a page name ClearCache.aspx and call above function in page_load method. So when ever I want to clear cache's contents I just call that page using URL.

Feel free to comment. Happy Coding !!!