C# 清除Cookies

C# 清除Cookies


现在越来越多的网站使用了Cookie技术,它给我们带来方便的同时,也给我们带来了一点小麻烦。
比如Gmail的自动登录。
在网上没有找到合适的代码,于是就自己写了一个清除Cookie的函数(包括一个重载函数)。

CleanCookies方法

public bool CleanCookies(string URLStr, int ExType)

清除指定或全部Cookie数据

返回值

类型:BOOL

用于判断操作是否完成。

true表示成功 false表示失败

参  数

URLStr

类型:string

指定要删除的网址Cookies,赋空时,删除所有Cookies数据 

ExType

类型:int

指定浏览器的类型

0为Internet Explorer 1为FireFox

重  载

public bool CleanCookies()

清除所有Cookie 默认IE浏览器 

范  例

清除网站http://mail.google.com/的Cookie数据 使用IE浏览器

CleanCookies("mail.google.com",0); 

清除网站http://mail.google.com/的Cookie数据 使用FireFox浏览器

CleanCookies("mail.google.com",1);

清除全部Cookie数据 使用IE浏览器

CleanCookies("",0);

使用重载函数删除所有Cookie数据

CleanCookies();

程  序

//清空126网站的Cookie数据

if (CleanCookies("www.126.com", 0))

         MessageBox.Show("清除成功");

else

         MessageBox.Show("清除失败");

源代码

public bool CleanCookies(string URLStr, int ExType)

        {

            //定义变量

            string CookiesPath, FindDirctroy, OsTypeStr;

            string UserProfile;

            string XPCookiesPath, VistaCookiesPath;

            long OsType;


            //获取用户配置路径

            UserProfile = Environment.GetEnvironmentVariable("USERPROFILE");

            MessageBox.Show(UserProfile);

            //获取操作系统类型

            OsType = Environment.OSVersion.Version.Major;


            //解析地址

            if (URLStr == "")

                FindDirctroy = "";

            else

            {

                //用"."分割字符

                char[] separator = { '.' };

                string[] MyWords;

                MyWords = URLStr.Split(separator);

                //选取其中的关键字

                try

                {

                    FindDirctroy = MyWords[1];

                }

                catch

                {

                    FindDirctroy = "";

                    //如果出错提示

                    MessageBox.Show("输入的网址格式不正确。");

                }

                //测试使用

                MessageBox.Show(FindDirctroy);

            }


            //判断浏览器类型

            if(ExType==0)

            {

                //IE浏览器

                XPCookiesPath = @"\Cookies\";

                VistaCookiesPath = @"\AppData\Roaming\Microsoft\Windows\Cookies\";

            }

            else if(ExType == 1)

            {

                //FireFox浏览器

                XPCookiesPath = @"\Application Data\Mozilla\Firefox\Profiles\";

                VistaCookiesPath = @"\AppData\Roaming\Mozilla\Firefox\Profiles\";

                FindDirctroy = "cookies";

            }

            else

            {

             XPCookiesPath = "";

             VistaCookiesPath = "";

             return false;

            }


            //判断操作系统类型

            if (OsType == 5)

            {

                //系统为XP

                OsTypeStr = "Microsoft Windows XP";

                CookiesPath = UserProfile + XPCookiesPath;

                //测试使用

                MessageBox.Show(CookiesPath);

            }

            else if (OsType == 6)

            {

                //系统为Vista

                OsTypeStr = "Microsoft Windows Vista";

                CookiesPath = UserProfile + VistaCookiesPath;

                //测试使用

                MessageBox.Show(CookiesPath);

            }

            else if (OsType == 7)

            {

                //系统为Win 7

                OsTypeStr = "Microsoft Windows 7";

                CookiesPath = UserProfile + VistaCookiesPath;

                //测试使用

                MessageBox.Show(CookiesPath);

            }

            else

            {

                //未识别之操作系统

                OsTypeStr = "Other OS Version";

                CookiesPath = "";

                return false;

            }


            //删除文件

            if (DeleteFileFunction(CookiesPath, FindDirctroy))

                return true;

            else

                return false;

        }

//重载函数

public bool CleanCookies()

        {

            if (CleanCookies("", 0))

                return true;

            else

                return false;

        }

private bool DeleteFileFunction(string filepath,string FindWords)

        {

            string Dstr;

            //下面这些字串例外

            string ExceptStr = "index.dat";

            //解析删除关键字

            if (FindWords == "")

                Dstr = "*.*";

            else

                Dstr = "*" + FindWords + "*";


            //删除cookie文件夹

            try

            {

                foreach (string dFileName in Directory.GetFiles(filepath,Dstr))

                {

                    if (dFileName == filepath + ExceptStr)

                        continue;

                    File.Delete(dFileName);

                }

            }

            catch (Exception e)

            {

                MessageBox.Show("Cookies删除失败!\n" + e.ToString());

                return false;

            }


            //深层遍历(解决Vista Low权限问题)

            string[] LowPath = Directory.GetDirectories(filepath);

            foreach (string ThePath in LowPath)

            {

                try

                {

                    foreach (string dFileName in Directory.GetFiles(ThePath, Dstr))

                    {

                        if (dFileName == filepath + ExceptStr)

                            continue;

                        File.Delete(dFileName);

                    }

                }

                catch (Exception e)

                {

                    MessageBox.Show("遍历文件删除失败!\n" + e.ToString());

                    return false;

                }

            }

            //测试使用

            MessageBox.Show("删除完成!");

            return true;

        }



C# 中,当你需要向服务器发送POST请求并设置Cookies(客户端存储的信息),可以使用HttpClient类配合CookieContainer来管理cookies。以下是一个简单的示例: ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; public async void SetCookiesHttpPost() { // 创建HttpClient实例 HttpClient client = new HttpClient(); // 创建CookieContainer实例 CookieContainer cookieContainer = new CookieContainer(); // 想要设置的Cookie,例如 "Key"="Value" Cookie cookie = new Cookie("Key", "Value"); cookieContainer.Add(new Uri("http://example.com"), cookie); // 将cookie关联到特定域名 // 使用CookieContainer处理饼干 client.DefaultRequestHeaders.Accept.Clear(); // 清除默认Accept头 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // 添加适当的媒体类型 client.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", cookieContainer.GetCookies(new Uri("http://example.com")).ToString()); // 添加Cookie到请求头 // 发送POST请求 HttpResponseMessage response = await client.PostAsync("http://example.com/endpoint", null); // 替换为你的实际URL // 检查响应状态和处理返回的cookies if (response.IsSuccessStatusCode) { Console.WriteLine($"Response status: {response.StatusCode}"); // 获取响应中的cookies,如果有的话 var receivedCookies = response.Headers.GetValues(HttpHeaderNames.SetCookie); foreach (var cookieStr in receivedCookies) { var newCookie = cookieContainer.GetCookies(new Uri(response.RequestMessage.RequestUri)).Cast<Cookie>().SingleOrDefault(c => c.Name == cookieStr); if (newCookie != null) { Console.WriteLine($"Received cookie: Name={newCookie.Name}, Value={newCookie.Value}"); } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值