I have a CookieContainer
extracted from a HttpWebRequest/HttpWebResponse session named CookieJar. I want my application to store cookies between runs, so cookies collected in the CookieContainer
on one run of the program will be used the next run, too.
I think the way to do this would be to somehow write the contents of a CookieContainer to disk. My question is:
- How can you write a CookieContainer to the disk? Are there built-in functions for this, or, if not, what are the approaches people have taken? Are there any classes available for simplifying this?
- Once you've written a CookieContainer to the disk, how do you load it back in for use?
UPDATE: The first answer has suggested serialization of the CookieContainer
. However, I am not very familiar with how to serialize and deserialize such complex objects. Could you provide some sample code? The suggestion was to utilise SOAPFormatter
.
I Haven't tried it but it has the attribute Serializable and so can be [de]serialized with .net binary serialization, e.g. SoapFormatter.
Here is the code snippet you asked for.
Looking at msdn it seems SoapFormatter is now deprecated in .net 3.5 and it recommends you use Binaryformatter. In the past I have found SoapFormatter useful as the file is readable which helps with diagnosis when deserialization fails! These formatters are sensitive to version changes even in the assembly version (so if you deserialize with one version of the framework upgrade the framework, then it might not deserialize, not sure), but there are ways around this with the Binder property if this becomes a problem. I believe they are primarily designed for short term persistance / remoting, but they might be good enough for you here.
The new DataContractSerializer does not seem to work with it so that is out.
An alternative would be to write a CookieContainerData class to [de]serialize with XmlSerializer and manually convert between this and CookieContainer.
Another alternative is to use Json serialization (Json.NET):
A class with a cookie:
Here is how to serialize it to Json:
This problem was bugging me for ages, nothing I could find worked. I worked it out, so putting that information out into the world.
Answer using BinaryFormatter: