csharp Serialize object to cookie

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class MyClass
{
	private int _MyProperty;
	public int MyProperty
	{
		get
		{
			return this._MyProperty;
		}
		set
		{
			this._MyProperty = value;
		}
	}
	
	public bool AnotherProperty { get; set; }
}

/// <summary>
/// Stores object in cookie
/// </summary>
/// <param name="filter"></param>
public void SaveToCookie()
{
	HttpCookie cookie = new HttpCookie("MyClass")
	{
		Expires = DateTime.Now.AddHours(24)
	};

	Stream stream = new MemoryStream();

	try
	{
		// Create a binary formatter and serialize the myClass into the memorystream
		IFormatter formatter = new BinaryFormatter();
		formatter.Serialize(stream, this);

		// Go to the beginning of the stream and fill a byte array with the contents of the memory stream
		stream.Seek(0, SeekOrigin.Begin);
		byte[] buffer = new byte[stream.Length];
		stream.Read(buffer, 0, (int)stream.Length);

		// Store the buffer as a base64 string in the cookie
		cookie.Value = Convert.ToBase64String(buffer);

		// Add the cookie to the current http context
		HttpContext.Current.Response.Cookies.Add(cookie);
	}
	catch (Exception)
	{
		//do nothing
	}
	finally
	{
		stream.Close();
	}
}

/// <summary>
/// Retrieves object from cookie
/// </summary>
/// <returns></returns>
public static MyClass RestoreFromCookie()
{
	// Always remember to check that the cookie is not empty
	HttpCookie cookie = HttpContext.Current.Request.Cookies["MyClass"];

	if (cookie != null)
	{
		// Convert the base64 string into a byte array
		byte[] buffer = Convert.FromBase64String(cookie.Value);

		// Create a memory stream from the byte array
		Stream steam = new MemoryStream(buffer);

		try
		{
			// Create a binary formatter and deserialize the
			// contents of the memory stream into MyClass
			IFormatter formatter = new BinaryFormatter();
			MyClass streamedClass = (MyClass)formatter.Deserialize(steam);
			return streamedClass;
		}
		finally
		{
			// ... and as always, close the stream
			steam.Close();
		}
	}
	return null;
}

Updated: Wednesday 18th May 2011, 03:52am

There are 0 comments

Leave a comment of your own

Comments are currently closed.