Introduction
This article shows how to read a file from Internet Explorer's cache, and write a file to the cache.
Reading from the cache
Retrieving the local cache file name of a URL is simple. You call GetUrlCacheEntryInfo
with the URL, and it will return the local file name. The function will return TRUE
if the URL is in the cache, and FALSE
otherwise. Then, you simply read the page and display it, or do whatever you want with it. Alternatively, you could use the function RetrieveUrlCacheEntryFile
or RetrieveUrlCacheEntryStream
to return the file or stream directly to your application.
CString strURL;
m_url.GetWindowText(strURL);
DWORD dwBufferSize = 4096;
LPINTERNET_CACHE_ENTRY_INFO lpCacheEntry =
(LPINTERNET_CACHE_ENTRY_INFO) new char[dwBufferSize];
lpCacheEntry->dwStructSize = dwBufferSize;
if (GetUrlCacheEntryInfo(strURL,lpCacheEntry,
&dwBufferSize) == TRUE)
{
m_browser.Navigate(lpCacheEntry->lpszLocalFileName,
NULL,NULL,NULL,NULL);
}
delete lpCacheEntry;
Writing files to the cache
Writing files to the cache is a little more complicated. It requires a couple function calls. One method is to use URLDownloadToCacheFile
. I am behind a proxy, and so URLDownloadToFile
will not work for me. The method I use is just as simple. You first call CreateUrlCacheEntry
with the URL and file type and a holder for the cache file name. The function will return a cache file name of where the URL is to be copied. Next, you write the data to the returned cache file. I use a simple local test page as the source of the file to be written, and copy its contents to the cache file. Finally, you call CommitUrlCacheEntry
to finalize the entry into the cache. When calling this method, you specify the URL, the cache file name returned in CreateUrlCacheEntry
, the expired and modified time if known, and a simple header. Use this header if none is known: (LPBYTE)"HTTP/1.0 200 OK\r\n\r\n"
.
CString strURL;
m_url.GetWindowText(strURL);
char lpszFileName[MAX_PATH+1];
if (CreateUrlCacheEntry(strURL,0,"htm",
lpszFileName,0) == TRUE)
{
char ch;
ifstream fp_read("testme.html", ios_base::in);
ofstream fp_write(lpszFileName, ios_base::out);
while(fp_read.eof() != true)
{
fp_read.get(ch);
if((int)ch == 0x0D)
continue;
if (!fp_read.eof())fp_write.put(ch);
}
fp_read.close();
fp_write.close();
FILETIME ftExpireTime;
ftExpireTime.dwHighDateTime = 0;
ftExpireTime.dwLowDateTime = 0;
FILETIME ftModifiedTime;
ftModifiedTime.dwHighDateTime = 0;
ftModifiedTime.dwLowDateTime = 0;
if (CommitUrlCacheEntry(strURL,lpszFileName,
ftExpireTime,ftModifiedTime,
NORMAL_CACHE_ENTRY,
(LPBYTE)"HTTP/1.0 200 OK\r\n\r\n",
20, NULL, NULL) == TRUE)
{
m_browser.Navigate(lpszFileName,NULL,
NULL,NULL,NULL);
}
}
That's all there is to it!