using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
namespace AuthClient.com.authclient.utils
{
class IeCookieUtil
{
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved);
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
public static string getInfoByCookie(string type)
{
//string cookStr = "cbAccount=11111;systemAccountId=0;systemCode=aaa";
string cookStr = GetCookieString(BrowserUrlConfig.tymhCas);//传参是获取cookie的URL
if (cookStr != null && !"".Equals(cookStr))
{
string[] sArray = Regex.Split(cookStr, ";", RegexOptions.IgnoreCase);
foreach (string cookie in sArray)
{
string[] cookieArry = Regex.Split(cookie, "=", RegexOptions.IgnoreCase);
foreach (string cook in cookieArry)
{
string tmpCook = cook.Trim();
if (tmpCook == type)
{
return cookieArry[1];
}
}
}
}
return "";
}
private static string GetCookieString(string url)
{
// Determine the size of the cookie
uint datasize = 256;
StringBuilder cookieData = new StringBuilder((int)datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x2000, IntPtr.Zero))
{
if (datasize < 0)
return null;
// Allocate stringbuilder large enough to hold the cookie
cookieData = new StringBuilder((int)datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, IntPtr.Zero))
return null;
}
return cookieData.ToString();
}
public static void setIECookie(string url, string name, string value)
{
System.Net.Cookie netCookie = new System.Net.Cookie(HttpUtility.UrlEncode(name).Replace("+", ""), HttpUtility.UrlEncode(value), "; expires = Session GMT", "/");
InternetSetCookie(url, null, netCookie.ToString());
}
}
}
string cbAccount = IeCookieUtil.getInfoByCookie("cas_username_cookie");//读取key为cas_username_cookie的cookie值
IeCookieUtil.setIECookie(url,"driverVersion", "1.0.1");//网址、key、值