/// <summary> /// Clears the cache of the web browser /// </summary> public static void ClearCache() { const int errorInsufficientBuffer = 0x7A; DeleteGroups(); // Start to delete URLs that do not belong to any group. var cacheEntryInfoBufferSizeInitial = 0; ClearCacheNativeMethods.FindFirstUrlCacheEntry(null, IntPtr.Zero, ref cacheEntryInfoBufferSizeInitial); // should always fail because buffer is too small if (Marshal.GetLastWin32Error() != errorInsufficientBuffer) { return; } var cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial; var cacheEntryInfoBuffer = Marshal.AllocHGlobal(cacheEntryInfoBufferSize); try { var enumHandle = ClearCacheNativeMethods.FindFirstUrlCacheEntry(null, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial); if (enumHandle != IntPtr.Zero) { bool more; do { var internetCacheEntry = Marshal.PtrToStructure <ClearCacheNativeMethods.InternetCacheEntryInfoA>(cacheEntryInfoBuffer); cacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize; ClearCacheNativeMethods.DeleteUrlCacheEntry(internetCacheEntry.SourceUrlName); more = ClearCacheNativeMethods.FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial); if (!more && Marshal.GetLastWin32Error() == errorInsufficientBuffer) { cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial; cacheEntryInfoBuffer = Marshal.ReAllocHGlobal(cacheEntryInfoBuffer, (IntPtr)cacheEntryInfoBufferSize); more = ClearCacheNativeMethods.FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial); } } while (more); } } finally { Marshal.FreeHGlobal(cacheEntryInfoBuffer); } }
/// <summary> /// Delete the groups first. /// Groups may not always exist on the system. /// For more information, visit the following Microsoft Web site: /// http://msdn.microsoft.com/library/?url=/workshop/networking/wininet/overview/cache.asp /// By default, a URL does not belong to any group. Therefore, that cache may become /// empty even when the CacheGroup APIs are not used because the existing URL does not belong to any group. /// </summary> private static void DeleteGroups() { // Indicates that all of the cache groups in the user's system should be enumerated const int cacheGroupSearchAll = 0x0; // Indicates that all the cache entries that are associated with the cache group // should be deleted, unless the entry belongs to another cache group. const int cacheGroupFlagFlushUrlOnDelete = 0x2; long groupId = 0; var enumHandle = ClearCacheNativeMethods.FindFirstUrlCacheGroup(0, cacheGroupSearchAll, IntPtr.Zero, 0, ref groupId, IntPtr.Zero); if (enumHandle == IntPtr.Zero) { return; } do { ClearCacheNativeMethods.DeleteUrlCacheGroup(groupId, cacheGroupFlagFlushUrlOnDelete, IntPtr.Zero); } while (ClearCacheNativeMethods.FindNextUrlCacheGroup(enumHandle, ref groupId, IntPtr.Zero)); }