C# 如何从 windows.form 中删除 Cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/912741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete Cookies from windows.form?
提问by Proximo
I am working with the Webbrowser control on a windows.form application written in C#. I would like to write a method for deleting the cookies from the Webbrowers control after it visits a certain site. Unfortunately, I don't know how to do that exactly and haven't found a lot of help on the internet.
我正在使用 C# 编写的 windows.form 应用程序上的 Webbrowser 控件。我想编写一个方法,用于在访问某个站点后从 Webbrowers 控件中删除 cookie。不幸的是,我不知道如何准确地做到这一点,也没有在互联网上找到很多帮助。
If anyone has experience actually doing this, not just hypothetical because it might be trickier than it seems, I don't know.
如果有人有实际这样做的经验,而不仅仅是假设,因为它可能比看起来更棘手,我不知道。
int count = webBrowser2.Document.Cookie.Length;
webBrowser2.Document.Cookie.Remove(0,count);
I would just assume something like the above code would work but I guess it won't. Can anyone shed some light on this whole cookie thing?
我只是假设上面的代码会起作用,但我想不会。任何人都可以对整个饼干的事情有所了解吗?
采纳答案by 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.
如果您启用了 JavaScript,您只需使用此代码片段来清除 Web 浏览器当前所在站点的 cookie。
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 bookmarkletfor clearing cookies.
回答by Peter Lange
Does the webbrowser control show pages form mutliple sites that you, as a developer, are not in control of, or are you just using the web browser control to view custom HTML pages created within your application?
webbrowser 控件显示的页面是否形成了您作为开发人员无法控制的多个站点,或者您只是使用 web 浏览器控件来查看在您的应用程序中创建的自定义 HTML 页面?
If it is the former, cookies are directly tied to the domain that sets them, and as such to delete these cookies you would need to monitor the users's cookie directory and delete any new cookies created, a track changes to existing cookies.
如果是前者,cookie 直接与设置它们的域相关联,因此要删除这些 cookie,您需要监视用户的 cookie 目录并删除创建的任何新 cookie,跟踪对现有 cookie 的更改。
If it is the later, you can always send the webbrowser control to a custom page that deletes the cookies with either server-side scripting (if available in your application) or JavaScript.
如果是后者,您始终可以将 webbrowser 控件发送到自定义页面,该页面使用服务器端脚本(如果在您的应用程序中可用)或 JavaScript 删除 cookie。
回答by Jordan Milne
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());}}}})())")
回答by Jordan Milne
Try using this:
尝试使用这个:
System.IO.File.Delete(Environment.SpecialFolder.Cookies.ToString() + "cookiename");
回答by Eyal
I'm using this code and it works without JavaScript. It's doing the same things as the JavaScript, but in VB.NET. Also, no navigation needed.
我正在使用这段代码,它在没有 JavaScript 的情况下工作。它和 JavaScript 做同样的事情,但在 VB.NET 中。此外,不需要导航。
For Each cookie As String In Document.Cookie.Split(";"c)
Dim domain As String = "." + url.Host
While domain.Length > 0
Dim path As String = url.LocalPath
While path.Length > 0
Document.Cookie = cookie.Split("="c)(0).Trim & "= ;expires=Thu, 30-Oct-1980 16:00:00 GMT;path=" & path & ";domain=" & domain
path = path.Substring(0, path.Length - 1)
End While
Select Case domain.IndexOf(".")
Case 0
domain = domain.Substring(1)
Case -1
domain = ""
Case Else
domain = domain.Substring(domain.IndexOf("."))
End Select
End While
Next
The only real difference from the JavaScript is where, instead of just expiring cookie=value
, I specifically search for the =
and expire cookie=
. This is important for expiring cookies that have no value.
与 JavaScript 的唯一真正区别在于cookie=value
,我专门搜索了=
和 expire ,而不仅仅是 expiring cookie=
。这对于使没有价值的 cookie 过期很重要。
Pitfalls:
陷阱:
- You can only delete the cookies of the website to which you have navigated.
- If the page is redirected to a different domain, the cookies you remove might be from the redirected domain. Or not, it's a race between the redirect and your code.
- Don't access
Document
untilReadyState = WebBrowserReadyState.Complete
, otherwise Document will be Nothing and the dereference will throw an exception. - Probably lots of others, but this code works great for me.
- 您只能删除您浏览过的网站的 cookie。
- 如果页面被重定向到不同的域,则您删除的 cookie 可能来自重定向的域。或者不是,这是重定向和您的代码之间的竞争。
- 不要访问
Document
untilReadyState = WebBrowserReadyState.Complete
,否则 Document 将是 Nothing 并且取消引用将引发异常。 - 可能还有很多其他人,但这段代码对我来说非常有用。
Firefox with the View Cookies Add-Onhelped a lot in debugging specific web pages.
带有查看 Cookie 附加组件的Firefox在调试特定网页方面有很大帮助。
回答by mr.baby123
I found a solution, for deleting all cookies. the example found on the url, deletes the cookies on application (process) startup.
我找到了一个解决方案,用于删除所有 cookie。在 url 上找到的示例在应用程序(进程)启动时删除 cookie。
http://mdb-blog.blogspot.com/2013/02/c-winforms-webbrowser-clear-all-cookies.html
http://mdb-blog.blogspot.com/2013/02/c-winforms-webbrowser-clear-all-cookies.html
The solution is using InternetSetOptionFunction to announce the WEBBROWSER to clear all its content.
解决方案是使用InternetSetOption函数通知 WEBBROWSER 清除其所有内容。
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:
请注意,这只会清除 MSDN INTERNET_OPTION_SUPPRESS_BEHAVIOR上所写的特定 PROCESS 的 cookie :
A general purpose option that is used to suppress behaviors on a process-wide basis.
一个通用选项,用于在进程范围的基础上抑制行为。
回答by diangelisj
After a great time finding how destroy sessions in webbrowser C# I'm have sucessfull using a code:
在找到如何在 webbrowser C# 中销毁会话之后,我使用代码成功了:
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());}}}})())")
how says for Jordan Milne in this topic above.
在上面的这个主题中,乔丹米尔恩怎么说。
In my application I need use webbrowser1.navigate("xxx");
在我的应用程序中,我需要使用 webbrowser1.navigate("xxx");
here don't work if you use the C# properties.
如果您使用 C# 属性,则此处不起作用。
i hope you find it useful this information.
我希望你觉得这些信息很有用。
回答by Sergey Belikov
I modified the solution from here: http://mdb-blog.blogspot.ru/2013/02/c-winforms-webbrowser-clear-all-cookies.html
我从这里修改了解决方案: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
您在流程开始时调用 SupressCookiePersist 和 EndBrowserSession 以在浏览器关闭时清除 cookie,如下所述: Facebook multi account
回答by Thomas Levesque
A variant of other proposed answers, which doesn't require unsafe code or manual marshalling:
其他建议答案的变体,不需要不安全的代码或手动编组:
private static void SuppressCookiePersistence()
{
int flag = INTERNET_SUPPRESS_COOKIE_PERSIST;
if (!InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, ref flag, sizeof(int)))
{
var ex = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
throw ex;
}
}
const int INTERNET_OPTION_SUPPRESS_BEHAVIOR = 81;
const int INTERNET_SUPPRESS_COOKIE_PERSIST = 3;
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, ref int flag, int dwBufferLength);
回答by FarhadMohseni
web browser control based on Internet Explorer , so when we delete IE cookies,web browser cookies deleted too. so by thisanswer you can try this:
基于 Internet Explorer 的浏览器控件,所以当我们删除 IE cookie 时,web 浏览器 cookie 也被删除。所以通过这个答案你可以试试这个:
System.Diagnostics.Process.Start("CMD.exe","/C RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");