I’m planning on doing a series of posts called ‘2 Minute Tutorials’. I always get frustrated when searching for information on the Internet. Sometimes, I just want a simple explanation, and a code example that I can utilize immediately. This is what I hope to provide in this series of posts, which will be mostly related to Windows Phone 7, C#, and C++.
In this particular installment, I’m going to take you through the process of storing and retrieving information on the Windows Phone 7 platform – a certain requirment should you intend developing a WP7 application. You can store information on the phones local file system quite easily. This may be required for saving such things as user information like usernames and passwords to services such as Twitter, or application specific preferences such as a preferred language or orientation.
This functionality is provided by the IsolatedStorageSettings class contained in the System.IO.IsolatedStorage namespace. It’s ‘isolated’, because it can only be accessed by your application, not by any others. If you need to share information between applications, you’ll need to store it on the web somewhere – this offers local, isolated storage only.
IsolatedStorageSettings allows you to store name/value pairs in a dictionary. This data will always be there, even after powering off the phone. It will remain in the file system until you either remove it, or you uninstall the application to which it belongs.
Here’s an example of storing an item called ‘username’:
using System.IO.IsolatedStorage;
...
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings.Add("username", "jimmy");
Simple. It’s just as easy to retrieve the data again:
string username = (string) settings['username'];
Some important things to remember:
- Your application will throw an exception if you try to retrieve a value that is not present so you should always handle this case.
- You can save anything, even Objects.
- You have to explicitly cast your data when you retrieve it.
That’s it. It’s that simple to store and retrieve information on the local file system of a device running Windows Phone 7.
See here for the MSDN documention on IsolatedStorageSettings.