User Settings in Isolated Storage
If the standard Settings class and propertyBindings is not enough.
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
namespace Library.IOPath
{
/// <summary>
/// Various user settings. Call static methods to Load and Save this (xmlSerialize into IsolatedStorage - so must be public serializable).
/// </summary>
[Serializable]
public class UserSettings
{
#region My Settings
public bool IsSorted { get; set; }
#endregion
#region Static methods to load and save settings to isolated storage
private static UserSettings _instance;
private const string _fileName = "Settings.xml";
/// <summary>
/// Gets or sets a singleton instance.
/// </summary>
public static UserSettings Instance
{
get
{
if (_instance == null) _instance = LoadSettings();
return _instance;
}
}
private static IsolatedStorageFile IsolatedStore
{
get
{
return IsolatedStorageFile.GetUserStoreForAssembly();
//.net 1 style...
//IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Roaming, null, null);
}
}
public static void SaveSettings(UserSettings settings)
{
var isoStore = IsolatedStore;
var serializer = new XmlSerializer(typeof(UserSettings));
using (var file = new IsolatedStorageFileStream(_fileName, FileMode.Create, isoStore))
{
serializer.Serialize(file, settings);
}
_instance = settings;
}
public static UserSettings LoadSettings()
{
var isoStore = IsolatedStore;
if (isoStore.GetFileNames(_fileName).Length == 0) //does not exist
return new UserSettings();
using (var file =
new IsolatedStorageFileStream(_fileName, FileMode.Open, isoStore))
{
try
{
var serializer = new XmlSerializer(typeof(UserSettings));
return (UserSettings)serializer.Deserialize(file);
}
catch (InvalidOperationException) //the xml was invalid
{
return new UserSettings();
}
}
}
#endregion
}
}