Jerry Nixon @Work: Mango Sample: Isolated Storage

Jerry Nixon on Windows

Monday, November 7, 2011

Mango Sample: Isolated Storage

imageStoring Windows Phone application data is a pretty normal requirement. If you want it to persist across sessions, or even phone reboots, you really have three options:

  1. Save to the Cloud
  2. Save to Isolated Storage
  3. Save to Local Database

Each is right for certain scenarios. But in this article, I will ONLY walk through Isolated Storage. Isolated Storage is a file folder dedicated to your application. It’s size limited is the phone’s available space (be good). Interact with it like System.IO.Directory.

Common request: Can I read, write, or save to the Phone’s global folders instead of those specific to my application? No – get that into your head. Windows Phone doesn’t allow third-party applications to tinker with core phone asset.

Isolated Storage has two areas for you:

  1. System.IO.IsolatedStorage.IsolatedStorageSettings This provides a simple name/value dictionary that serializes whatever you put in it. This might tempt you to put everything in it. But don’t. Use it for settings. If you have to persist objects, even small ones, use a storage file. Here’s an interesting discussion on use.
  2. System.IO.IsolatedStorage.IsolatedStorageFile This gives developers a real File / Folder API. Organize objects into folders if you want. Then serialize your objects and save them to files. When your app restarts, they are still there. As a matter of practice, persist data as-you-go as it can take time (seconds) to save.

Side bar: Any data that you store in InsolatedStorage must be serializable, either directly or by using data contracts. No exceptions. More on contracts.

How to use IsolatedStorageSettings

image

Get the real code here.

How to use IsolatedStorageFile

image

Get the real code here.

Be sure to reference System.XAML.Serialization. This code is generic. This might be all you ever need for IsolatedStorage. Ensure path is unique for each object; otherwise, it’s that simple. Just copy, paste, and get programming.

Here’s a sample implementation:

image

Don’t Forget This

First: Any serializable object can be persisted to a file – large or small. Writing and reading will take time. Plan on this delay! The Phone will terminate applications if Load or Close take too long. So, Read outside of Load. And, Save along the way; keep Close fast.

Finally: There are many ways to serialize objects. You can use XML, binary, JSON, and much more. The choice is up to you. My samples use XML because it reliable, fast, and native. But, there’s nothing wrong if you pick another approach (for a reason).