This post is Day #15 in a series called the 31 Days of Windows Phone.
Yesterday, we talked about tombstoning our applications, so that they appear to be running in the background. Today, I’m going to cover a great way to store your data locally on the phone, using Isolated Storage.
What Is Isolated Storage?
Isolated Storage is not a new concept. It’s been used in Silverlight since version 2. It’s basically a way to store data or files on the local file system. It’s “isolated” because only your application has access to the data. If you have two applications, and you want to share data between them, you’d better have some kind of cloud-based service that can share that data for you. Applications will not have the ability to share, call, or interact with other applications on the device.
Settings vs. Files
There are two ways to store your data locally. The first is through a library of name/value pairs. This is called IsolatedStorageSettings. The second way is through actual file and folder creation. This is called IsolatedStorageFile. The image below (courtesy of MSDN) helps illustrate this briefly, and then I will dive into examples of each.
IsolatedStorageSettings
For many purposes, this might be the only storage that you need. IsolatedStorageSettings allows you to store name/value pairs in a dictionary (without ANY setup, mind you), that you can retrieve later. This data is persisted across application stop/start, powering the phone off, etc. It’s there until you remove it, or the user uninstalls your application. One important thing to remember is that you can’t retrieve a value until it’s been added to the library. In each of my examples, you’re going to see code that checks to see if the value exists first, before retrieving it. Here’s an example of the code you’d need to save a user’s preference for receiving email updates from your application. I have one CheckBox that allows a user to decide, and events that store that value to IsolatedStorage.
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using System.IO.IsolatedStorage; namespace Day15_IsolatedStorage { public partial class MainPage : PhoneApplicationPage { IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings; // Constructor public MainPage() { InitializeComponent(); InitializeSettings(); } private void InitializeSettings() { if (settings.Contains("emailFlag")) { EmailFlag.IsChecked = (bool)settings["emailFlag"]; } else settings.Add("emailFlag", false); } private void EmailFlag_Unchecked(object sender, RoutedEventArgs e) { settings["emailFlag"] = false; } private void EmailFlag_Checked(object sender, RoutedEventArgs e) { settings["emailFlag"] = true; } } }
As you can see, this is incredibly simple. Here’s a few things to remember:
- Trying to retrieve a value from IsolatedStorageSettings will throw an error if it hasn’t already been created. Make sure you initialize your settings, or ALWAYS check the .Contains property first.
- You can save anything you want in the Settings. I saved a boolean value in my example, but you could also save a Customer object, or any other else you can come up with.
- Remember that you have to explicitly cast your data when you retrieve it. You’ll notice that I have to cast my bool value before I can use it. You’re saving the object, but the storage does NOT save the type. That’s up to you when you want to use it again.
- Setting a value is the same as adding a value to the library. The “settings.Add()” statement is actually unnecessary, but I added it so that you could see the syntax.
So that’s about it. IsolatedStorageSettings is pretty straightforward. Save name/value pairs with very little actual code. Creating and saving files is a little more complicated, but still surprisingly simple. Let’s take a look at that now.
IsolatedStorageFile
Using IsolatedStorageFile is the mechanism you can use for storing actual FILES on the user’s device. In my example, I’m going to create a text file in a subdirectory, and then retrieve the contents of that file. We have the ability to create and delete folders, subfolders, and files. This is going to seem like a TON more code, but it’s actually pretty simple. We’re creating a new IsolatedStorageFile object, and then writing it to the drive using an IsolatedStorageFileStream. I’ve added comments to my code inline, so that you can see what is happening a little easier. I have two events, one that saves the file, and one that reads it:
using System.IO.IsolatedStorage; using System.IO; private void SaveButton_Click(object sender, RoutedEventArgs e) { //Obtain a virtual store for application IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication(); //Create new subdirectory fileStorage.CreateDirectory("textFiles"); //Create a new StreamWriter, to write the file to the specified location. StreamWriter fileWriter = new StreamWriter(new IsolatedStorageFileStream("textFiles\newText.txt", FileMode.OpenOrCreate, fileStorage)); //Write the contents of our TextBox to the file. fileWriter.WriteLine(writeText.Text); //Close the StreamWriter. fileWriter.Close(); } private void GetButton_Click(object sender, RoutedEventArgs e) { //Obtain a virtual store for application IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication(); //Create a new StreamReader StreamReader fileReader = null; try { //Read the file from the specified location. fileReader = new StreamReader(new IsolatedStorageFileStream("textFiles\newText.txt", FileMode.Open, fileStorage)); //Read the contents of the file (the only line we created). string textFile = fileReader.ReadLine(); //Write the contents of the file to the TextBlock on the page. viewText.Text = textFile; fileReader.Close(); } catch { //If they click the view button first, we need to handle the fact that the file hasn't been created yet. viewText.Text = "Need to create directory and the file first."; } }
This doesn’t seem like much of an amazing trick until you leave the application, come back, and try to load the file again (and it’s still there!).
So there you have it. We have two simple storage mechanisms available to us in Windows Phone 7. IsolatedStorageSettings and IsolatedStorageFile. I’d be interested to hear the creative ways you are leveraging these storage structures in your application. Please leave comments!
Download the Code
This example code incorporates both the Settings and File storage code shown above in one project.
Leave a Reply to prabhjot Cancel reply