Serializing Objects to Isolated Storage in Silverlight 2

[Cross posted from: SilverlightForBusiness.net ]

Silverlight 2 does not have a BinaryFormatter like the full framework does so you have to take a different approach to serializing data to Isolated Storage.

However there is a simple solution by using the DataContractSerializer.  You will need to add a reference to System.Runtime.Serialization.  This will serialize the object to an Xml format and is what Silverlight uses when you add a service reference.

So if we have an object called Person, we can use the DataContract and DataMember attributes to mark it up as follows:

[DataContract]
public class Person
{
    [DataMember]
    public int PersonId { get; set; }
    [DataMember]
    public string Name { get; set; }
    
}

You can then use the DataContractSerializer as follows to save Person data to Iso storage:

Person p = new Person() { PersonId = 1, Name = "Fred" };
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForSite())
{
    IsolatedStorageFileStream stream = store.CreateFile("Person.dat");
    DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
    serializer.WriteObject(stream, p);
    stream.Close();
}
MessageBox.Show("Data Saved");

And the following to read it:

Person p;
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForSite())
{
    IsolatedStorageFileStream stream = store.OpenFile("Person.dat", FileMode.Open);
    DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
    p = (Person)serializer.ReadObject(stream);
    stream.Close();
}
MessageBox.Show("Data Loaded");
TextBlock1.Text = p.Name + " " + p.PersonId;

If you want to make this more generic you could create a generic method as follows:

private void SaveData<T>(T dataToSave,string fileName)
{
    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForSite())
    {
        IsolatedStorageFileStream stream = store.CreateFile(fileName);
        DataContractSerializer serializer = new DataContractSerializer(typeof(T));
        serializer.WriteObject(stream, dataToSave);
        stream.Close();
    }
}

Then you can call it as follows:

SaveData<ObservableCollection<Person>>(people, "People.dat");
SaveData<Person>(person, "Person.dat");

Cheers

Ian

posted @ Thursday, November 27, 2008 11:26 AM

Print

Comments on this entry:

# re: Serializing Objects to Isolated Storage in Silverlight 2

Left by watch tv at 12/13/2008 12:43 AM
Gravatar
Great code.
Comments have been closed on this topic.