GetCookie将信息提取到String
我正试图通过Set-Cookie从我得到的cookie获取数字信息我需要&om=-&lv=1341532178340&xrs=
这里的数字
这就是我提出的:
string key = ""; ArrayList list = new ArrayList(); foreach (Cookie cookieValue in agent.LastResponse.Cookies) { list.Add(cookieValue); } String[] myArr = (String[])list.ToArray(typeof(string)); foreach (string i in myArr) { // Here we call Regex.Match. Match match = Regex.Match(i, @"&lv=(.*)&xrs=", RegexOptions.IgnoreCase); // Here we check the Match instance. if (match.Success) { // Finally, we get the Group value and display it. key = match.Groups[1].Value; } } agent.GetURL("http://site.com/" + key + ".php");
我遇到的问题是我无法将ArrayList更改为String(错误是:“源数组中至少有一个元素无法转换为目标数组类型。”),我想你们可以帮助我,也许你们可以想出一种方法来修复它或更好的代码来做到这一点?
非常感谢!
使用第一个循环,您将构建一个包含Cookie
实例的ArrayList
。 当您尝试在第二个循环之前执行时,不可能简单地将Cookie
从Cookie
转换为string
。
获取所有cookie值的简单方法是使用LINQ:
IEnumerable cookieValues = agent.LastResponse.Cookies.Select(x => x.Value);
如果您仍在使用.NET Framework 2.0,则需要使用循环:
List cookieValues = new List (); foreach (Cookie cookie in agent.LastResponse.Cookies) { cookieValues.Add(cookie.Value); }
然后,您可以像以前一样迭代这个集合。 但是,您是否知道如果多个cookie与您的正则表达式匹配,那么最后匹配的cookie将存储到key
? 当有多个匹配的cookie时,不知道你希望它如何工作,但如果你只是想要第一个,你可以再次使用LINQ使你的代码更简单,并在一个查询中几乎完成你需要的一切:
var cookies = agent.LastResponse.Cookies; string key = cookies.Cast() .Select(x => Regex.Match(x.Value, @"&lv=(.*)&xrs=", RegexOptions.IgnoreCase)) .Where(x => x.Success) .Select(x => x.Groups[1].Value) .FirstOrDefault();
如果没有匹配,则key
将为null,否则,它将包含第一个匹配项。 Cast
位是类型推断的必要条件 – 我相信agent.LastResponse.Cookies
返回一个CookieCollection
实例,它不实现IEnumerable
。