Clearing IE Cache Programatically

Posted on 2004-04-29
Last Modified: 2013-11-13
I want to clear the internet Explorer Cache through an application, can i do this using any Windows API functions, if so how i do this?

Plz help me As soon as possible, since is ugrently required..

Umesh Timoli.
Question by:timoliumesh
LVL 35

Accepted Solution

[ fanpages ] earned 50 total points
ID: 10946952
Hi timoliumesh,

I'm not aware what language you are using but here's some sample code written by Andrew Baker for MS-Excel (VBA):


The following code can be used to query and delete files in the internet cache (including cookies). A demonstration routine can be found at the bottom of this post. Note, the enumerated type eCacheType is not supported in Excel 97, but can be changed to a list of Public Constants eg. Public Const eNormal = &H1&.

Option Explicit

'--------------------------Types, consts and structures
Private Const ERROR_CACHE_FIND_FAIL As Long = 0
Private Const ERROR_CACHE_FIND_SUCCESS As Long = 1
Private Const ERROR_FILE_NOT_FOUND As Long = 2
Private Const ERROR_ACCESS_DENIED As Long = 5
Private Const MAX_CACHE_ENTRY_INFO_SIZE As Long = 4096

Private Const LMEM_FIXED As Long = &H0
Private Const LMEM_ZEROINIT As Long = &H40

Public Enum eCacheType
    eNormal = &H1&
    eEdited = &H8&
    eTrackOffline = &H10&
    eTrackOnline = &H20&
    eSticky = &H40&
    eSparse = &H10000
    eCookie = &H100000
    eURLHistory = &H200000
    eURLFindDefaultFilter = 0&
End Enum

Private Type FILETIME
    dwLowDateTime As Long
    dwHighDateTime As Long
End Type

    dwStructSize As Long
    lpszSourceUrlName As Long
    lpszLocalFileName As Long
    CacheEntryType  As Long         'Type of entry returned
    dwUseCount As Long
    dwHitRate As Long
    dwSizeLow As Long
    dwSizeHigh As Long
    LastModifiedTime As FILETIME
    ExpireTime As FILETIME
    LastAccessTime As FILETIME
    LastSyncTime As FILETIME
    lpHeaderInfo As Long
    dwHeaderInfoSize As Long
    lpszFileExtension As Long
    dwExemptDelta  As Long
End Type

'--------------------------Internet Cache API
Private Declare Function FindFirstUrlCacheEntry Lib "Wininet.dll" Alias "FindFirstUrlCacheEntryA" (ByVal lpszUrlSearchPattern As String, lpFirstCacheEntryInfo As Any, lpdwFirstCacheEntryInfoBufferSize As Long) As Long
Private Declare Function FindNextUrlCacheEntry Lib "Wininet.dll" Alias "FindNextUrlCacheEntryA" (ByVal hEnumHandle As Long, lpNextCacheEntryInfo As Any, lpdwNextCacheEntryInfoBufferSize As Long) As Long
Private Declare Function FindCloseUrlCache Lib "Wininet.dll" (ByVal hEnumHandle As Long) As Long
Private Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" Alias "DeleteUrlCacheEntryA" (ByVal lpszUrlName As String) As Long

'--------------------------Memory API
Private Declare Function LocalAlloc Lib "kernel32" (ByVal uFlags As Long, ByVal uBytes As Long) As Long
Private Declare Function LocalFree Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSource As Any, ByVal dwLength As Long)
Private Declare Function lstrcpyA Lib "kernel32" (ByVal RetVal As String, ByVal Ptr As Long) As Long
Private Declare Function lstrlenA Lib "kernel32" (ByVal Ptr As Any) As Long

'Purpose     :  Deletes the specified internet cache file
'Inputs      :  sCacheFile              The name of the cache file
'Outputs     :  Returns True on success.
'Author      :  Andrew Baker
'Date        :  03/08/2000 19:14
'Notes       :
'Revisions   :

Function InternetDeleteCache(sCacheFile As String) As Boolean
    InternetDeleteCache = CBool(DeleteUrlCacheEntry(sCacheFile))
End Function

'Purpose     :  Returns an array of files stored in the internet cache
'Inputs      :  eFilterType             An enum which filters the files returned by their type
'Outputs     :  A one dimensional, one based, string array containing the names of the files
'Author      :  Andrew Baker
'Date        :  03/08/2000 19:14
'Notes       :
'Revisions   :

Function InternetCacheList(Optional eFilterType As eCacheType = eNormal) As Variant
    Dim lhFile As Long, lBufferSize As Long, lptrBuffer As Long
    Dim sCacheFile As String
    Dim asURLs() As String, lNumEntries As Long

    'Determine required buffer size
    lBufferSize = 0
    lhFile = FindFirstUrlCacheEntry(0&, ByVal 0&, lBufferSize)
        'Allocate memory for ICEI structure
        lptrBuffer = LocalAlloc(LMEM_FIXED, lBufferSize)
        If lptrBuffer Then
            'Set a Long pointer to the memory location
            CopyMemory ByVal lptrBuffer, lBufferSize, 4
            'Call first find API passing it the pointer to the allocated memory
            lhFile = FindFirstUrlCacheEntry(vbNullString, ByVal lptrBuffer, lBufferSize)        '1 = success
            If lhFile <> ERROR_CACHE_FIND_FAIL Then
                'Loop through the cache
                    'Copy data back to structure
                    CopyMemory ICEI, ByVal lptrBuffer, Len(ICEI)
                    If ICEI.CacheEntryType And eFilterType Then
                        sCacheFile = StrFromPtrA(ICEI.lpszSourceUrlName)
                        lNumEntries = lNumEntries + 1
                        If lNumEntries = 1 Then
                            ReDim asURLs(1 To 1)
                            ReDim Preserve asURLs(1 To lNumEntries)
                        End If
                        asURLs(lNumEntries) = sCacheFile
                    End If
                    'Free memory associated with the last-retrieved file
                    Call LocalFree(lptrBuffer)
                    'Call FindNextUrlCacheEntry with buffer size set to 0.
                    'Call will fail and return required buffer size.
                    lBufferSize = 0
                    Call FindNextUrlCacheEntry(lhFile, ByVal 0&, lBufferSize)
                    'Allocate and assign the memory to the pointer
                    lptrBuffer = LocalAlloc(LMEM_FIXED, lBufferSize)
                    CopyMemory ByVal lptrBuffer, lBufferSize, 4&
                Loop While FindNextUrlCacheEntry(lhFile, ByVal lptrBuffer, lBufferSize)
            End If
        End If
    End If
    'Free memory
    Call LocalFree(lptrBuffer)
    Call FindCloseUrlCache(lhFile)
    InternetCacheList = asURLs
End Function

'Purpose     :  Converts a pointer an ansi string into a string.
'Inputs      :  lptrString                  A long pointer to a string held in memory
'Outputs     :  The string held at the specified memory address
'Author      :  Andrew Baker
'Date        :  03/08/2000 19:14
'Notes       :
'Revisions   :

Function StrFromPtrA(ByVal lptrString As Long) As String
    'Create buffer
    StrFromPtrA = String$(lstrlenA(ByVal lptrString), 0)
    'Copy memory
    Call lstrcpyA(ByVal StrFromPtrA, ByVal lptrString)
End Function

'Demonstration routine
Sub Test()
    Dim avURLs As Variant, vThisValue As Variant
    On Error Resume Next
    'Return an array of all internet cache files
    avURLs = InternetCacheList
    For Each vThisValue In avURLs
        'Print files
        Debug.Print CStr(vThisValue)
    'Return the an array of all cookies
    avURLs = InternetCacheList(eCookie)
    If MsgBox("Delete cookies?", vbQuestion + vbYesNo) = vbYes Then
        For Each vThisValue In avURLs
            'Delete cookies
            InternetDeleteCache CStr(vThisValue)
            Debug.Print "Deleted " & vThisValue
        For Each vThisValue In avURLs
            'Print cookie files
            Debug.Print vThisValue
    End If
End Sub



Assisted Solution

stitch2802 earned 50 total points
ID: 10978799
Hi Umesh,

Try this:

// From MSDN (see:KB 815718 @;en-us;815718)
     // Pointer to a GROUPID variable
     GROUPID groupId = 0;
     // Local variables
     DWORD cacheEntryInfoBufferSizeInitial = 0;
    DWORD cacheEntryInfoBufferSize = 0;
    int *cacheEntryInfoBuffer = 0;
    INTERNET_CACHE_ENTRY_INFOA *internetCacheEntry;
    HANDLE enumHandle = NULL;
    BOOL returnValue = false;

     // Delete the groups first.
    // Groups may not always exist on the system.
    // For more information, visit the following Microsoft Web site:
    // 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.              
    enumHandle = FindFirstUrlCacheGroup(0, CACHEGROUP_SEARCH_ALL, 0, 0, &groupId, 0);

     // If there are no items in the Cache, you are finished.
     if (enumHandle != NULL && ERROR_NO_MORE_ITEMS == GetLastError())
          return 0;
     // Loop through Cache Group, and then delete entries.
          // Delete a particular Cache Group.
          returnValue = DeleteUrlCacheGroup(groupId, CACHEGROUP_FLAG_FLUSHURL_ONDELETE, 0);
          if (!returnValue && ERROR_FILE_NOT_FOUND == GetLastError())
               returnValue = FindNextUrlCacheGroup(enumHandle, &groupId, 0);
          if (!returnValue && (ERROR_NO_MORE_ITEMS == GetLastError() || ERROR_FILE_NOT_FOUND == GetLastError()))
     // Start to delete URLs that do not belong to any group.
     enumHandle = FindFirstUrlCacheEntry(NULL, 0, &cacheEntryInfoBufferSizeInitial);
     if (enumHandle != NULL && ERROR_NO_MORE_ITEMS == GetLastError())
                return 0;
     cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;
     internetCacheEntry =  (INTERNET_CACHE_ENTRY_INFOA *)malloc(cacheEntryInfoBufferSize);
     enumHandle = FindFirstUrlCacheEntry(NULL, internetCacheEntry, &cacheEntryInfoBufferSizeInitial);
          cacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize;          
          returnValue = DeleteUrlCacheEntry(internetCacheEntry->lpszSourceUrlName);                    
          if (!returnValue)
               returnValue = FindNextUrlCacheEntry(enumHandle, internetCacheEntry, &cacheEntryInfoBufferSizeInitial);
          DWORD dwError = GetLastError();
          if (!returnValue && ERROR_NO_MORE_ITEMS == dwError)
          if (!returnValue && cacheEntryInfoBufferSizeInitial > cacheEntryInfoBufferSize)
               cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;
               internetCacheEntry =  (INTERNET_CACHE_ENTRY_INFOA *)realloc(internetCacheEntry, cacheEntryInfoBufferSize);
               returnValue = FindNextUrlCacheEntry(enumHandle, internetCacheEntry, &cacheEntryInfoBufferSizeInitial);                        
     MessageBox("Temporary Internet Files cleared.",0, MB_OK);


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now