An easy way to save state in Silverlight and Windows Phone7

In many cases you need to save some state in your application. In Silverlight the best way to do this is to write to IsolatedStorage. After writing the same code many times for saving different types of objects to IsolatedStorage I started to look for a simpler/more generic way of doing it, and came up with a solution which makes me do like this:

//Write any object to IsolatedStorage
IsolatedStorageManager.WriteObjectToFile("aFileName",anyObject);

//Read any object back from IsolatedStorage
var objectFromFile = IsolatedStorageManager.ReadObjectFromFile<AnyClass>("aFileName");

This makes it very easy to write whatever object to IsolatedStorage. Below you can find my implementation of the IsolatedStorageManager

using System.IO;
using System.IO.IsolatedStorage;
using System.Text;

namespace IsolatedStorageSample
{
 public static class IsolatedStorageManager
 {
 public static void WriteObjectToFile<T>(string filename, T data)
 {
 string xml = Serialization.Serialize<T>(data);
 IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
 using (IsolatedStorageFileStream writer = file.CreateFile(filename))
 {
 byte[] content = Encoding.UTF8.GetBytes(xml);
 writer.Write(content, 0, content.Length);
 writer.Close();
 }
 }

 public static T ReadObjectFromFile<T>(string filename)
 {
 string xml = null;
 IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
 using (IsolatedStorageFileStream stream = file.OpenFile(filename, FileMode.Open))
 {
 using (StreamReader reader = new StreamReader(stream))
 {
 xml = reader.ReadToEnd();
 }
 }
 return Serialization.Deserialize<T>(xml);
 }
 }
}

The IsolatedStorageManager class depends on a class named Serialization which looks like this:

using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace IsolatedStorageSample
{
 public static class Serialization
 {
 public static string Serialize<T>(T objectToSerialize)
 {
 if (objectToSerialize == null)
 return null;
 using (MemoryStream ms = new MemoryStream())
 {
 DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());

 serializer.WriteObject(ms, objectToSerialize);
 ms.Position = 0;

 using (StreamReader reader = new StreamReader(ms))
 {
 return reader.ReadToEnd();
 }
 }
 }

 public static T Deserialize<T>(string json)
 {
 if (string.IsNullOrEmpty(json))
 return default(T);

 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
 T obj = (T)serializer.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(json)));
 return obj;
 }
 }
}

In order to get this to compile you need to add a reference to System.ServiceModel.Web

This code works great in both regular silverlight and in windows phone 7.