The IsolatedStorageSettings class is pretty good. It allows you to access without problems to the settings of your app, with a nice casting and without having to deal with files. But if you’re using it a lot in different parts of the code, it’s probably better to enclose it in a bigger class, more useful to you. I’ve developed this, which can be pretty useful:
public static class Config { private static readonly string SomeConfigElementKey = "MYKEY"; private static string _someConfigElement; public string SomeConfigElement { get { return GenericGetFromConfig(SomeConfigElementKey, ref _someConfigElement); } set { GenericSaveToConfig(SomeConfigElementKey, ref _someConfigElement, value); } } private static T GenericGetFromConfig(string Key, ref T element) where T : new() { if (element != null) return element; IsolatedStorageSettings config = IsolatedStorageSettings.ApplicationSettings; try { if (!config.TryGetValue(Key, out element)) { element = new T(); config.Add(Key, element); config.Save(); } } catch (InvalidCastException) { config.Remove(Key); } catch (Exception) { } if (element == null) element = new T(); return element; } private static void GenericSaveToConfig(string Key, ref T element, T value) where T : new() { if (value == null) return; IsolatedStorageSettings conf = IsolatedStorageSettings.ApplicationSettings; try { element = value; if (conf.Contains(Key)) conf[Key] = value; else conf.Add(Key, value); conf.Save(); } catch (Exception) { } } }
It’s pretty simple. The main part of the class are the methods GenericGetFromConfig and GenericSaveToConfig. The first one always returns the element you requested. If it does not exist, the method creates it and saves it in the Isolated storage. It also controls exceptions, so you will never get null or an error.
The second one does more or less the same: save an element to the isolated storage. If it exists, the method updates it avoiding duplicates. As the previous method, it’s failsafe.
Why the ref T element in both of the functions? That’s there to avoid calling IsolatedStorageSettings every time you need an object. You can have a look at the example of SomeConfigElement. There is a private static variable who acts as an intermediate between your code and the IsolatedStorage. Whenever you want to get a value, the function first checks if the static variable is null. If it is, it reads from IsolatedStorage. But if not, that means that we’ve already retrieved the value and don’t need to call again to IsolatedStorage.
That variable is always synced with the IsolatedStorage, so you don’t have to worry about anything when retrieving data from the settings. You only have to get the value from Config.WhateverVariable and that’s it. Clean, safe, useful and fast.