在 WPF 中使用 C# 代码删除 IE 缓存和 Cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16167984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deleting IE Cache and Cookies using C# Code in WPF
提问by lookitskris
I am using a WebBrowser control in my WPF application and I am looking to clear the IE cookie cache from code.
我在 WPF 应用程序中使用 WebBrowser 控件,并且希望从代码中清除 IE cookie 缓存。
I have attempted to use the following code
我曾尝试使用以下代码
string[] Cookies = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
foreach (string currentFile in Cookies)
{
try
{
System.IO.File.Delete(currentFile);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This deletes the files from the specified folder, but when I navigate back using the WebBrowser control, the cookies reappear as though they were never deleted.
这会从指定的文件夹中删除文件,但是当我使用 WebBrowser 控件导航回来时,cookie 会重新出现,就好像它们从未被删除过一样。
This might be the right result, as I am assuming that the Environment.SpecialFolder.Cookies folder is in AppData which is a current snapshot of what the user is up to.
这可能是正确的结果,因为我假设 Environment.SpecialFolder.Cookies 文件夹位于 AppData 中,它是用户正在做什么的当前快照。
If I open up IE, and do a hard delete of cookies and cache I get the expected output in my app.
如果我打开 IE,并硬删除 cookie 和缓存,我会在我的应用程序中得到预期的输出。
Is there a way to do this action in code?
有没有办法在代码中执行此操作?
采纳答案by Smaug
The Microsoft KB Article will help you better and clear the entire Cache.
Microsoft KB 文章将帮助您更好地清除整个缓存。
However, You can try the following solution too.
但是,您也可以尝试以下解决方案。
string[] InterNetCache = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache));
回答by user2787612
Using below function one can delete cookie for the certain host name. If whole cache needs to be cleared then condition "if(sourceUrlName.Contains(hostEntry) && sourceUrlName.ToLower().Contains("cookie"))" should be removed.
使用以下功能可以删除特定主机名的cookie。如果需要清除整个缓存,则应删除条件“ if(sourceUrlName.Contains(hostEntry) && sourceUrlName.ToLower().Contains("cookie"))”。
/// <summary>
/// Internets the set cookie.
/// </summary>
/// <param name="lpszUrlName">Name of the LPSZ URL.</param>
/// <param name="lpszCookieName">Name of the LPSZ cookie.</param>
/// <param name="lpszCookieData">The LPSZ cookie data.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetSetCookie(string lpszUrlName, string lpszCookieName, string lpszCookieData);
/// <summary>
/// Internets the get cookie.
/// </summary>
/// <param name="lpszUrl">The LPSZ URL.</param>
/// <param name="lpszCookieName">Name of the LPSZ cookie.</param>
/// <param name="lpszCookieData">The LPSZ cookie data.</param>
/// <param name="lpdwSize">Size of the LPDW.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookie(string lpszUrl, string lpszCookieName, StringBuilder lpszCookieData, ref int lpdwSize);
/// <summary>
/// Finds the first URL cache entry.
/// </summary>
/// <param name="lpszUrlSearchPattern">The LPSZ URL search pattern.</param>
/// <param name="lpFirstCacheEntryInfo">The lp first cache entry info.</param>
/// <param name="lpdwFirstCacheEntryInfoBufferSize">Size of the LPDW first cache entry info buffer.</param>
/// <returns>IntPtr.</returns>
[DllImport(@"wininet",
SetLastError = true,
CharSet = CharSet.Auto,
EntryPoint = "FindFirstUrlCacheEntryA",
CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr FindFirstUrlCacheEntry(
[MarshalAs(UnmanagedType.LPTStr)] string lpszUrlSearchPattern,
IntPtr lpFirstCacheEntryInfo,
ref int lpdwFirstCacheEntryInfoBufferSize);
/// <summary>
/// Finds the next URL cache entry.
/// </summary>
/// <param name="hFind">The h find.</param>
/// <param name="lpNextCacheEntryInfo">The lp next cache entry info.</param>
/// <param name="lpdwNextCacheEntryInfoBufferSize">Size of the LPDW next cache entry info buffer.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
[DllImport(@"wininet",
SetLastError = true,
CharSet = CharSet.Auto,
EntryPoint = "FindNextUrlCacheEntryA",
CallingConvention = CallingConvention.StdCall)]
public static extern bool FindNextUrlCacheEntry(
IntPtr hFind,
IntPtr lpNextCacheEntryInfo,
ref int lpdwNextCacheEntryInfoBufferSize);
/// <summary>
/// Deletes the URL cache entry.
/// </summary>
/// <param name="lpszUrlName">Name of the LPSZ URL.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
[DllImport(@"wininet",
SetLastError = true,
CharSet = CharSet.Auto,
EntryPoint = "DeleteUrlCacheEntryA",
CallingConvention = CallingConvention.StdCall)]
public static extern bool DeleteUrlCacheEntry(
IntPtr lpszUrlName);
/// <summary>
/// Clears the IE cache.
/// </summary>
/// <param name="url">The URL.</param>
public static void ClearIECache(string url)
{
try
{
// No more items have been found.
const int ERROR_NO_MORE_ITEMS = 259;
string hostEntry = new Uri(url).Host;
// Local variables
int cacheEntryInfoBufferSizeInitial = 0;
int cacheEntryInfoBufferSize = 0;
IntPtr cacheEntryInfoBuffer = IntPtr.Zero;
INTERNET_CACHE_ENTRY_INFOA internetCacheEntry;
IntPtr enumHandle = IntPtr.Zero;
bool returnValue = false;
// Start to delete URLs that do not belong to any group.
enumHandle = FindFirstUrlCacheEntry(null, IntPtr.Zero, ref cacheEntryInfoBufferSizeInitial);
if (enumHandle == IntPtr.Zero && ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error())
return;
cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;
cacheEntryInfoBuffer = Marshal.AllocHGlobal(cacheEntryInfoBufferSize);
enumHandle = FindFirstUrlCacheEntry(null, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial);
while (true)
{
internetCacheEntry = (INTERNET_CACHE_ENTRY_INFOA)Marshal.PtrToStructure(cacheEntryInfoBuffer, typeof(INTERNET_CACHE_ENTRY_INFOA));
string sourceUrlName = Marshal.PtrToStringAnsi(internetCacheEntry.lpszSourceUrlName);
cacheEntryInfoBufferSizeInitial = cacheEntryInfoBufferSize;
if (sourceUrlName.Contains(hostEntry) && sourceUrlName.ToLower().Contains("cookie"))
{
DeleteUrlCacheEntry(internetCacheEntry.lpszSourceUrlName);
}
returnValue = FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial);
if (!returnValue && ERROR_NO_MORE_ITEMS == Marshal.GetLastWin32Error())
{
break;
}
if (!returnValue && cacheEntryInfoBufferSizeInitial > cacheEntryInfoBufferSize)
{
cacheEntryInfoBufferSize = cacheEntryInfoBufferSizeInitial;
cacheEntryInfoBuffer = Marshal.ReAllocHGlobal(cacheEntryInfoBuffer, (IntPtr)cacheEntryInfoBufferSize);
returnValue = FindNextUrlCacheEntry(enumHandle, cacheEntryInfoBuffer, ref cacheEntryInfoBufferSizeInitial);
}
}
Marshal.FreeHGlobal(cacheEntryInfoBuffer);
}
catch
{
//error
}
}
/// <summary>
/// Struct INTERNET_CACHE_ENTRY_INFOA
/// </summary>
[StructLayout(LayoutKind.Explicit, Size = 80)]
public struct INTERNET_CACHE_ENTRY_INFOA
{
[FieldOffset(0)]
public uint dwStructSize;
[FieldOffset(4)]
public IntPtr lpszSourceUrlName;
[FieldOffset(8)]
public IntPtr lpszLocalFileName;
[FieldOffset(12)]
public uint CacheEntryType;
[FieldOffset(16)]
public uint dwUseCount;
[FieldOffset(20)]
public uint dwHitRate;
[FieldOffset(24)]
public uint dwSizeLow;
[FieldOffset(28)]
public uint dwSizeHigh;
[FieldOffset(32)]
public System.Runtime.InteropServices.ComTypes.FILETIME LastModifiedTime;
[FieldOffset(40)]
public System.Runtime.InteropServices.ComTypes.FILETIME ExpireTime;
[FieldOffset(48)]
public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;
[FieldOffset(56)]
public System.Runtime.InteropServices.ComTypes.FILETIME LastSyncTime;
[FieldOffset(64)]
public IntPtr lpHeaderInfo;
[FieldOffset(68)]
public uint dwHeaderInfoSize;
[FieldOffset(72)]
public IntPtr lpszFileExtension;
[FieldOffset(76)]
public uint dwReserved;
[FieldOffset(76)]
public uint dwExemptDelta;
}

