Clear web browser cookies winforms C#

2020-02-15 09:42发布

问题:

How I can clear cookies for web browser control winforms C# , is there any way to clear cookies problematically in winforms web browser control

回答1:

You can disable cache (including cookies) before navigating to the site. To do so, you can use InternetSetOption API function and set the value of INTERNET_OPTION_SUPPRESS_BEHAVIOR(81) option to INTERNET_SUPPRESS_COOKIE_PERSIST(3) value.

Example

The following example, works like starting a new session. While I've logged in to the outlook.com on my machine, but when I open this application and browse outlook.com after disabling cookies and cache, it works like starting a new session and I need to login to outlook.com:

//using System.Runtime.InteropServices;
[DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption,
    IntPtr lpBuffer, int dwBufferLength);
private void Form1_Load(object sender, EventArgs e)
{
    var ptr = Marshal.AllocHGlobal(4);
    Marshal.WriteInt32(ptr, 3);
    InternetSetOption(IntPtr.Zero, 81, ptr, 4);
    Marshal.Release(ptr);
    webBrowser1.Navigate("https://outlook.com");
}

To find more information about these flags, take a look at Windows Internet Option Flags.

Note: You can find a VB.NET version of this answer, here in my other post.