How to delete Cookies from windows.form?

Solution 1:

If you have JavaScript enabled you can just use this code snippet to clear to clear the cookies for the site the webbrowser is currently on.

webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")

It's derived from this bookmarklet for clearing cookies.

Solution 2:

I modified the solution from here: http://mdb-blog.blogspot.ru/2013/02/c-winforms-webbrowser-clear-all-cookies.html

Actually, you don't need an unsafe code. Here is the helper class that works for me:

public static class WinInetHelper
{
    public static bool SupressCookiePersist()
    {
        // 3 = INTERNET_SUPPRESS_COOKIE_PERSIST 
        // 81 = INTERNET_OPTION_SUPPRESS_BEHAVIOR
        return SetOption(81, 3);
    }

    public static bool EndBrowserSession()
    {
        // 42 = INTERNET_OPTION_END_BROWSER_SESSION 
        return SetOption(42, null);
    }

    static bool SetOption(int settingCode, int? option)
    {
        IntPtr optionPtr = IntPtr.Zero;
        int size = 0;
        if (option.HasValue)
        {
            size = sizeof (int);
            optionPtr = Marshal.AllocCoTaskMem(size);
            Marshal.WriteInt32(optionPtr, option.Value);
        }

        bool success = InternetSetOption(0, settingCode, optionPtr, size);

        if (optionPtr != IntPtr.Zero) Marshal.Release(optionPtr);
        return success;
    }

    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool InternetSetOption(
        int hInternet,
        int dwOption,
        IntPtr lpBuffer,
        int dwBufferLength
    );
}

You call SupressCookiePersist somewhere at the start of the process and EndBrowserSession to clear cookies when browser is closed as described here: Facebook multi account

Solution 3:

I found a solution, for deleting all cookies. the example found on the url, deletes the cookies on application (process) startup.

http://mdb-blog.blogspot.com/2013/02/c-winforms-webbrowser-clear-all-cookies.html

The solution is using InternetSetOption Function to announce the WEBBROWSER to clear all its content.

int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
int* optionPtr = &option;

bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
if (!success)
{
    MessageBox.Show("Something went wrong !>?");
}

Note, that clears the cookies for the specific PROCESS only as written on MSDN INTERNET_OPTION_SUPPRESS_BEHAVIOR:

A general purpose option that is used to suppress behaviors on a process-wide basis.