WP7 and IsolatedStorage

If you want to store data on your device, you’ll need IsolatedStorage. This is a sandbox storage for each application which means no application can read data belonging to another.
Also, you can’t browse the filesystem on your device – you only get access to your own application’s file.
Thus: Isolated storage.

There are various ways of going about using it (I believe someone is even making a local database based on IsolatedStorage).
The two basic ways are storing your data in the applications setting store or in a custom file.

Application settings

IsolatedStorage provides a way to store objects using IsolatedStorageSettings.ApplicationSettings, this is the easiest way of storing simple data. You just add your data to the settings store like so:
IsolatedStorageSettings.ApplicationSettings.Add(“myProperty”, value);
IsolatedStorageSettings.ApplicationSettings.Save();

The value object is then serialized down to disk automatically when calling Save() and can be read back thusly:
List<string> mydata = (List<string>)IsolatedStorageSettings.ApplicationSettings[“myProperty”];

Using files

This is basic IO really. You open up a stream and write to it.

using(IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()){
   using(IsolatedStorageFileStream fs = storage.CreateFile(“myfile.wp”)){
       using(StreamWriter writer = new StreamWriter(fs)){
          XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
          serializer.Serialize(writer, myStringList);
       }
    }
}

This example merely serializes a list of strings to xml located in IsolatedStorage.
Reading a file back is the almost the same basic code.

using(IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()){
   using(IsolatedStorageFileStream fs = storage.OpenFile(“myfile.wp”, FileMode.Open)){
      XDocument doc = XDocument.Load(fs);
      XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
      List<string> myData = (List<string>)serializer.Deserialize(doc.CreateReader());
   }
}

I like dealing with objects so I usually use serialization or Xml. That way, I can work with the objects themselves and bind them to various controls either by binding the objects themselves or using LINQ To Xml. Using text files with various formatting usually leads to a lot of overhead to do simple updates to the data.

Hopefully this helps out some of the new people that are flooding to the WP7 platform 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: