GetCookie将信息提取到String

时间:2012-07-07 20:41:59

标签: c# cookies

我正在尝试通过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(错误是:“源数组中至少有一个元素无法转换为目标数组类型。”),我想你们可以帮忙我也许你可以想出办法解决它或更好的代码来做到这一点?

非常感谢!

1 个答案:

答案 0 :(得分:3)

使用第一个循环,您构建的ArrayList包含Cookie个实例。正如您在第二个循环之前尝试做的那样,无法简单地从Cookie转换为string

获取所有cookie值的简单方法是使用LINQ:

IEnumerable<string> cookieValues = agent.LastResponse.Cookies.Select(x => x.Value);

如果您仍在使用.NET Framework 2.0,则需要使用循环:

List<string> cookieValues = new List<string>();
foreach (Cookie cookie in agent.LastResponse.Cookies)
{
    cookieValues.Add(cookie.Value);
}

然后,您可以像以前一样迭代这个集合。但是,您是否知道如果多个cookie与您的正则表达式匹配,那么最后匹配的cookie将存储到key?当有多个匹配的cookie时,不知道你想要它如何工作,但如果你只想要第一个,你可以再次使用LINQ使你的代码更简单,并在一个查询中做你需要的几乎所有事情: / p>

var cookies = agent.LastResponse.Cookies;
string key = cookies.Cast<Cookie>()
    .Select(x => Regex.Match(x.Value, @"&lv=(.*)&xrs=", RegexOptions.IgnoreCase))
    .Where(x => x.Success)
    .Select(x => x.Groups[1].Value)
    .FirstOrDefault();

如果没有匹配,key将为空,否则,它将包含第一个匹配。 Cast<Cookie>()位是启用类型推断所必需的 - 我相信agent.LastResponse.Cookies会返回CookieCollection的实例,但不会实现IEnumerable<Cookie>