Home > Uncategorized > Serializing a #CookieContainer in C#

Serializing a #CookieContainer in C#

If you are using C# to interact with websites, then a common pattern, is that you may log in with one request, and then perform an action with the logged in user with a second request. When you wish to repeat the action, then you may end up logging in again, even though you could have potentially recycled the session from the first log in, which saves both time, and bandwidth.

In order to do so, you will need to somehow store the cookies to disk, and then reload them for the second request.

Using XmlSerialiser in this case won’t work, since the Cookie object contains a Uri object, which is not serialisable, also JSON serialiser (Newtonsoft.JSON) is problematic, since it’s not precisely a 1:1 representation of the CookieContainer (I’m not exactly sure what it misses, please feel free to add comments below with your experience).

I found, that although marked as “obsolete” by Microsoft, the BinaryFormatter provides a faithful representation of the CookieCollection.

This is some code I wote to serialize a Cookie Collection

private static void StoreCookieCollection(IEnumerable cookies, string cookieFile)
{
	cookieFile = Path.GetTempPath() + cookieFile;
	if (File.Exists(cookieFile)) File.Delete(cookieFile);
	var formatter = new BinaryFormatter();
	var fs = new FileStream(cookieFile, FileMode.Create);
	formatter.Serialize(fs,cookies);
	fs.Close();
}

And the reverse for de-serializing it:

private static CookieCollection LoadCookieCollection(string cookieFile)
{
	cookieFile = Path.GetTempPath() + cookieFile;
	if (!File.Exists(cookieFile)) return null;
	var age = File.GetLastWriteTime(cookieFile);
	if (DateTime.Now - age > TimeSpan.FromDays(1)) return null; // a day old
	var formatter = new BinaryFormatter();
	CookieCollection cc;
	using (Stream reader = new FileStream(cookieFile, FileMode.Open))
	{
		cc = (CookieCollection)formatter.Deserialize(reader);
	}
	return cc;
}

Bon apetit!

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment