I want to export a CookieContainer to JSON using Newtonsoft.Json but unfortunately CookieContainer hasn\'t an enumerator or stuff, so I can\'t cycle through it ...
<
The first answer did not work for a portable project. So here's option 2, also uses reflection
using System.Linq;
using System.Collections;
using System.Reflection;
using System.Net;
public static CookieCollection GetAllCookies(this CookieContainer container)
{
var allCookies = new CookieCollection();
var domainTableField = container.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name == "m_domainTable");
var domains = (IDictionary)domainTableField.GetValue(container);
foreach (var val in domains.Values)
{
var type = val.GetType().GetRuntimeFields().First(x => x.Name == "m_list");
var values = (IDictionary)type.GetValue(val);
foreach (CookieCollection cookies in values.Values)
{
allCookies.Add(cookies);
}
}
return allCookies;
}
1) I also tried
var domainTableField = container.GetType().GetRuntimeField("m_domainTable");
but it returned null.
2) You can iterate through domains.Keys and use container.GetCookies() for all keys. But I've had problems with that, because GetCookies expects Uri and not all my keys matched Uri pattern.