I have a List
of data. And I want to save it and retrieve it every time my app starts and exits respectively. What is the equivalent of Isola
You can use this class to store and load settings:
public static class ApplicationSettings
{
public static void SetSetting(string key, T value, bool roaming = true)
{
var settings = roaming ? ApplicationData.Current.RoamingSettings : ApplicationData.Current.LocalSettings;
settings.Values[key] = value;
}
public static T GetSetting(string key, bool roaming = true)
{
return GetSetting(key, default(T), roaming);
}
public static T GetSetting(string key, T defaultValue, bool roaming = true)
{
var settings = roaming ? ApplicationData.Current.RoamingSettings : ApplicationData.Current.LocalSettings;
return settings.Values.ContainsKey(key) &&
settings.Values[key] is T ?
(T)settings.Values[key] : defaultValue;
}
public static bool HasSetting(string key, bool roaming = true)
{
var settings = roaming ? ApplicationData.Current.RoamingSettings : ApplicationData.Current.LocalSettings;
return settings.Values.ContainsKey(key) && settings.Values[key] is T;
}
public static bool RemoveSetting(string key, bool roaming = true)
{
var settings = roaming ? ApplicationData.Current.RoamingSettings : ApplicationData.Current.LocalSettings;
if (settings.Values.ContainsKey(key))
return settings.Values.Remove(key);
return false;
}
}
But you can only save and load primitive types (bool, int, string, etc.). This is why you have to serialize your list to XML or another format which can be stored in a string. To serialize and deserialize an object to and from XML you can use these methods:
public static string Serialize(object obj)
{
using (var sw = new StringWriter())
{
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
return sw.ToString();
}
}
public static T Deserialize(string xml)
{
using (var sw = new StringReader(xml))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(sw);
}
}
See also Is there a way to store instances of own classes in the ApplicationSettings of a Windows Store app?