What is the best way of saving List<Object> in Windows 8 app

前端 未结 2 911
谎友^
谎友^ 2020-12-30 11:48

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

2条回答
  •  执念已碎
    2020-12-30 12:24

    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?

提交回复
热议问题