How to clear System.Windows.Forms.WebBrowser session data?

↘锁芯ラ 提交于 2019-11-29 20:11:43

To clear session (such as HttpOnly cookies), you can use InternetSetOption() from wininet.dll.

private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;

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

and use this method whenever need to clear session.

InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);
webBrowser1.Document.Window.Navigate(url);

I tried everything to clear the form data so the next user would not see the previous email address, etc. I ended up doing this to clear the cookies...

string[] theCookies = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
foreach (string currentFile in theCookies)
{
   try
   {
      System.IO.File.Delete(currentFile);
   }
   catch (Exception ex)
   {
   }
}
Jordan Milne

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 (I haven't yet found a way to clear session cookies other than this).

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.

In addition to this, you can delete the contents of the "C:\Documents and Settings\username\Cookies" folder (minus the index.dat, which is usually locked).

As for the cached data, it should be sufficient to just delete all of the files in "C:\Documents and Settings\username\Local Settings\Temporary Internet Files".

If you really need to be able to clear the cookies for all sites, you're probably better off using something like the axWebBrowser control in the long run.

webBrowser1.Document.Cookies = "" won't work. This call will not clear the cookie. webBrowser1.Document.Cookies = just works as document.cookie in javascript. You should find the cookie you want to clear, sa 'Session', use webBrowser1.Document.Cookies = "Session = ''"; It will just set the cookie to '', as you want.

Advait Purohit

Following solution worked for me -

webBrowser1.Document.ExecCommand("ClearAuthenticationCache", false, null);

This was suggested in following post for deleting cookies - https://stackoverflow.com/a/21512662/6291511

You can find more info regarding this here - https://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.execcommand(v=vs.110).aspx

Hope it helps!!!

Private Const INTERNET_OPTION_END_BROWSER_SESSION As Integer = 42

    <DllImport("wininet.dll", SetLastError:=True)>
    Public Shared Function InternetSetOption(hInternet As IntPtr, dwOption As Integer, lpBuffer As IntPtr, lpdwBufferLength As Integer) As Boolean
    End Function

    Private Sub WebBrowserFormName_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0)
    End Sub

Just posting for someone looking for this answer in VB. Happy coding!!!

You have to realise that the way "session state" is tracked, from the point of view of a web server, is by giving the client browser a cookie with a session-id in it. When the browser posts back to the server, that cookie allows the server to associate the request with a stored session state.

So the solution is to clear the cookies of the webBrowser control. Eg webBrowser1.Document.Cookies = "", that should work I think.

ASP.NET also has what it calls "cookieless sessions", which work by adding the session id to the url. So if that's the mechanism used by the server, you could try to filter that out of the url. But you won't see that much, it's mostly the cookie based session state.

Windows 7 uses index.dat files to store cookies and history so that Bill and his freinds at CIA central can snoop on you and have done all they can to ensure you can not delete these files and that after taking copies because 'Special Folders' are used and the .Dat files remain locked whilst windows is running.

This is not a perfect solution but it works to some degree with the full file names being in a List.

int DeletedCount = 0;
        int CouldNotDelete = 0;
        KillExplorer();
        foreach (string DatFile in DatFiles)
        {//Do not put break point or step into the code else explorer will start and the file will become locked again
            DirectoryInfo DInfo=new DirectoryInfo(DatFile.Replace("index.dat",""));
            FileAttributes OldDirAttrib = DInfo.Attributes;
            DInfo.Attributes  = FileAttributes.Normal;//Set to normal else can not delete
            FileInfo FInfo = new FileInfo(DatFile);
            FileAttributes OldFileAttrib = FInfo.Attributes;
            SetAttr(FInfo, FileAttributes.Normal);
            TryDelete(FInfo);
            SetAttr(FInfo, OldFileAttrib);//Sets back to Hidden,system,directory,notcontentindexed
            if (File.Exists(DatFile))
                CouldNotDelete++;
            else
                DeletedCount++;

        }
        if (DatFiles.Count>0)//Lets get explorer running again
            System.Diagnostics.Process.Start(DatFiles[DatFiles.Count - 1].Replace("index.dat", ""));
        else
            System.Diagnostics.Process.Start("explorer");
        System.Windows.Forms.MessageBox.Show("Deleted " + DeletedCount + " Index.dat files with " + CouldNotDelete + " Errors");


        return "Deleted " + DeleteFileCount + " Files ";
    }

    private void KillExplorer()
    {
        foreach (Process P in Process.GetProcesses())
        {//Kill both these process because these are the ones locking the files
            if (P.ProcessName.ToLower() == "explorer")
                P.Kill();
            if (P.ProcessName.ToLower() == "iexplore")
                P.Kill();
        }
    }

    private bool TryDelete(FileInfo Info)
    {
        try
        {
            Info.Delete();
            return true;
        }
        catch 
        {return false;}
    }

    private void SetAttr(FileInfo Info,FileAttributes Attr)
    {
        try
        {
            Info.Attributes = Attr;
        }
        catch { }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!