Windows Phone 7 - Isolated Storage and Persistance

4 September 2010

Recently, I've added persistence / data storage to my Windows Phone 7 application, making it infinitely more useful and it wasn't as hard as I expected.

In Windows Phone 7, there's two kinds of storage. Firstly, there's the State property bag which you can access from PhoneApplicationService.Current.State. However, as far as I know, this State bag is not saved when the phone is turned off, so for more permanent storage, we need to write to a file. Because WP7 apps run under partial trust, we don't get access to the underlying file system, but we have access to Isolated Storage.

We can read/write files to Isolated Storage as expected, and there is also the IsolatedStorageSettings.ApplicationSettings dictionary which is a good place to store (you guessed it) application settings or small chunks of string data.

The best way to get your classes into binary data which you can write to Isolated Storage is by using the DataContractSerializer, and decorating the class you want to write to the filesystem with the [DataContract] attribute, and the properties you want to persist with the [DataMember] attribute. To use the DataContractSerializer, you'll need to add a reference to the System.Runtime.Serialization assembly. Below is a quick example of a class ready to be serialized, and some code to write it to IsolatedStorage.

[DataContract]
public class MyClass : INotifyPropertyChanged
{
    private DateTime _startTime;
    [DataMember]
    public DateTime StartTime
    {
        get { return _startTime; }
        set
        {
            if (value != _startTime)
            {
                _startTime = value;
                NotifyPropertyChanged("StartTime");
            }
        }
    }
}

using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(SAVE_PATH, System.IO.FileMode.Create, appStorage))
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(MyClass));
        serializer.WriteObject(stream, this);
    }
}

Two more gotchas: your DataMembers must be declared as public (partial trust does not allow for private setters to be serialized with the DataContractSerializer), and note that the IsolatedStorage on the beta developer tools doesn't persist across emulator reboots, so don't panic if you restart the emulator and you find that the files you've written to IsolatedStorage no longer exist.

Tags: wp7

Add a Comment

No Comments