GetCookie extract information to a String

醉酒当歌 提交于 2019-12-30 07:46:40

问题


I'm trying to get the numbers information from a cookie I get by Set-Cookie I need &om=-&lv=1341532178340&xrs= the numbers here

This is what I came up with:

 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");

The issue I'm having is I cannot change ArrayList to String (the error is: "At least one element in the source array could not be cast down to the destination array type."), I thought you guys can help me maybe you can come up with a way to fix it or a better code to do that?

Thanks a lot!


回答1:


With first loop, you are building an ArrayList that contains Cookie instances. It's not possible to simply convert from Cookie to string as you are attempting to do just before the second loop.

A simple way to get values of all cookies is to use LINQ:

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

If you are still using .NET Framework 2.0, you will need to use a loop:

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

Then, you can iterate over this collection just like you previously were. However, are you aware that if multiple cookies match your regex, the last one that matches will be stored to the key? Don't know how exactly you want this to work when there are multiple cookies that match, but if you simply want the first one, you can again employ LINQ to make your code simpler and do almost everything you need in a single query:

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();

If there was no match, the key will be null, otherwise, it will contain the first match. The Cast<Cookie>() bit is necessary for type inference to kick in - I believe that agent.LastResponse.Cookies returns an instance of CookieCollection which does not implement IEnumerable<Cookie>.



来源:https://stackoverflow.com/questions/11378467/getcookie-extract-information-to-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!