mclafee
mclafee

Reputation: 1426

Winforms WebBrowser: how to delete cookies

i'm trying to delete cookies in webbrowser control. This code deleted the cookies file, but before restarting the program, the cookies are still in memory.

private void deleteCookies(string domain)
    {
        string cookiesPath =
            Environment.GetFolderPath(Environment.SpecialFolder.Cookies);
        string[] unWantedCookies = 
            Directory.GetFiles(cookiesPath, "*" + domain + "*");
        foreach (string cookie in unWantedCookies)
        {
            File.Delete(cookie);
        }
    }

I tried this code:

webBrowser1 = new WebBrowser();

But it didn't work. i guess it's somewhere in the environment variables, but where?

Upvotes: 1

Views: 3173

Answers (2)

Erx_VB.NExT.Coder
Erx_VB.NExT.Coder

Reputation: 4856

You really should not use File IO to delete cookies, as cookies are not actually files, but data in an index.dat file, there is a virtual file but it isn't real, and deleting it will not remove the cookie from memory (this is your problem) - it is also not advised to use javascript hack to do this.

You are better of looking into DeleteUrlCacheEntry to delete cookies, and loop through all cache items using FindFirst/NextUrlCacheEntry, once you start looping, look for cache items begining with "cookie: ", and then you can look further into the cookie name, creation time (modified, synced, last accessed, expiration, etc) to decide which cookies you want to delete.

There are many good examples of pre-written code on the internet that will allow you to loop and delete cache items in IE, so use any one of them, and all you'll need to do is add a filter before the DeleteUrlCacheEntry call to decide if you want to call DeleteUrlCacheEntry for that item or not, of course, if you do, it will not only delete the cache entry from the internal database, but it will also remove it from active memory, and you also will not get the "file is use" error, as it will release it from memory and usage before deleting it.

Let me knwo if you need more info or help. Once again, search for the DeleteUrlCacheEntry code for the particular language you want it for, hey, it even exists for VB6 so i'm sure you'll have no trouble finding a copy for c# :).

let me know how you get along.

Upvotes: 2

PhonicUK
PhonicUK

Reputation: 13844

Use WebBrowser.InvokeScript ( http://msdn.microsoft.com/en-us/library/cc491132.aspx ) to execute some Javascript that will wipe the cookies for the current page.

Upvotes: 0

Related Questions