'Convert a Cookie object in to string format and back

How can I convert a cookie/cookie collection in to its string representation? (in ASP.Net)

What I am looking for is

cookie-collection  => "name1=value1 expires=date1; name2=value2 path=/test"

and vice-versa.



Solution 1:[1]

Are you looking for something like this?

   //Convert to string
   HttpCookieCollection source = new HttpCookieCollection();
   string result = source.Cast<HttpCookie>().
                   Aggregate(string.Empty, (current, cookie) => 
                   current + string.Format("{0}={1} ", cookie.Name, cookie.Value));


   //Convert back to collection
   HttpCookieCollection dest = new HttpCookieCollection();
   foreach (var pair in result.Split(' '))
   {
        string[] cookies = pair.Split('=');
        dest.Add(new HttpCookie(cookies[0],cookies[1]));
   }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stecya