Search code examples
c#wpfcookieswebautomation

Delete Cookies from a Different Domain


I am working on a web automation tool. After the tool is run once the associated website creates cookies that break the automation if I try to run it again. Because of this I would like to delete the cookies before the automation starts. I do not have access to the domain that actually creates the cookies. Is this possible? I know how to manipulate cookies, but all of that logic fails when you try to access cookies from a different website.

Additionally, I do not want to create a WebBrowser control if I can avoid it. I am trying to do everything with httpWebRequests so that it looks nicer.


Solution

  • If your test environment is running on a Windows system (and it sounds like it is) you can use pInvoke to manipulate the cache. The following four methods are needed. Unfortunately the code is owned by the company I work for, not me, so I can't paste it all here. It involves iterating over entries in the cache using "FindFirstUrlCacheEntry" and "FindNextUrlCacheEntry". Check the cache entry to see if it is a cookie and if it belongs to the domain you're interested in, if it is you can delete it.

    [DllImport (@"wininet", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern IntPtr FindFirstUrlCacheEntry ([MarshalAs (UnmanagedType.LPTStr)] string searchPattern, IntPtr ptrCacheEntryInfo, ref int cacheEntryInfoSize);
    
    [DllImport (@"wininet", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    private static extern bool FindNextUrlCacheEntry (IntPtr ptrCacheHandler, IntPtr ptrCacheEntryInfo, ref int cacheEntryInfoSize);
    
    [DllImport (@"wininet", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
    private static extern bool FindCloseUrlCache (IntPtr ptrCacheEntryInfo);
    
    [DllImport ("wininet.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    private static extern bool DeleteUrlCacheEntry (IntPtr lpszUrlName);