by brad
18. October 2010 12:38
Today’s tip focuses on the IsolatedStorageSettings class, the easiest way to put data into isolated storage. If you have simple key-value based data that you want to persist in isolated storage, the IsolateStorageSettings class provides a convenient and easy-to-code alternative to to the manual serializing and deserializing that’s required to get more complex data into isolated storage.
The name of the class indicates that it is intended to be used for storing user-specific settings for your application, but it can be used for any key-value storage needs that your application may have.
Using the IsolatedStorageSettings object to store data is as simple as getting a reference to the object and using the Add method.
1: var settings = IsolatedStorageSettings.ApplicationSettings;
2: settings.Add("location", "STL");
3: settings.Add("email", "brad@example.com");
The same values can be read or updated by referencing the key used to store the data.
1: var settings = IsolatedStorageSettings.ApplicationSettings;
2: var location = settings["location"].ToString();
3: settings["email"] = "tutterow@example.com";
Note that the value stored is stored as an object, so you are certainly not limited to strings like the examples above. You can store anything you want and use the TryGetValue() method to get things back strongly-typed.
1: // Store
2: Person person = new Person { FirstName = "Brad", LastName = "Tutterow" };
3: settings.Add("user", person);
4:
5: // Retrieve
6: Person person2;
7: settings.TryGetValue<Person>("user", out person2);
It might be tempting to use the IsolatedStorageSettings object for all of your isolated storage needs, but for more complex, non-settings data, consider serializing and deserializing yourself. This will be clearer to someone else reading your code, give you greater flexibility, and keep you more in-line with the intent of the IsolatedStorageSetttings object.
Other Resources
More Tips