Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

windows-8

I have a List<class> of data. And I want to save it and retrieve it every time my app starts and exits respectively. What is the equivalent of IsolatedStorage (WP7) in Windows 8. How can I save these settings?

like image 548
Milan Aggarwal Avatar asked Oct 07 '12 12:10

Milan Aggarwal


2 Answers

In windows 8, you have to use the LocalFolder for your app, which you can access using:

StorageFolder folder = ApplicationData.Current.LocalFolder;

and then reference files saved there by using:

var fileToGet = await folder.GetFileAsync("nameOfFile.fileType");

I am currently in a similar situation in a project I am working on, where I want to store a List of custom objects to my Apps LocalFolder and have it reloaded later.

My solution was to serialize the list to an XML string, and store this in the App Folder. You should be able to adapt my methods:

static public string SerializeListToXml(List<CustomObject> List)
    {
        try
        {
            XmlSerializer xmlIzer = new XmlSerializer(typeof(List<CustomObject>));
            var writer = new StringWriter();
            xmlIzer.Serialize(writer, List);
            System.Diagnostics.Debug.WriteLine(writer.ToString());
            return writer.ToString();
        }

        catch (Exception exc)
        {
            System.Diagnostics.Debug.WriteLine(exc);
            return String.Empty;
        }

Now that you have the string you can save it a text file and put this in LocalStorage:

//assuming you already have a list with data called myList
await Windows.Storage.FileIO.WriteTextAsync("xmlFile.txt", SerializeListToXml(myList));

Now when you load your app again you can use the loading method mentioned above to get the xmlFile from LocalStorage, and then deserialize it to get your List back.

string listAsXml = await Windows.Storage.FileIO.ReadTextAsync(xmlFile.txt);
List<CustomObject> deserializedList = DeserializeXmlToList(listAsXml);

Again, adapt this to your needs:

public static List<CustomObject> DeserializeXmlToList(string listAsXml)
    {
        try
        {
            XmlSerializer xmlIzer = new XmlSerializer(typeof(List<CustomObject>));
            XmlReader xmlRead = XmlReader.Create(listAsXml);
            List<CustomObject> myList = new List<CustomObject>();
            myList = (xmlIzer.Deserialize(xmlRead)) as List<CustomObject>;
            return myList;
        }

        catch (Exception exc)
        {
            System.Diagnostics.Debug.WriteLine(exc);
            List<CustomObject> emptyList = new List<CustomObject>();
            return emptyList;
        }
    }
like image 146
J.B Avatar answered Nov 01 '22 12:11

J.B


You can use this class to store and load settings:

public static class ApplicationSettings
{
    public static void SetSetting<T>(string key, T value, bool roaming = true)
    {
        var settings = roaming ? ApplicationData.Current.RoamingSettings : ApplicationData.Current.LocalSettings;
        settings.Values[key] = value;
    }

    public static T GetSetting<T>(string key, bool roaming = true)
    {
        return GetSetting(key, default(T), roaming);
    }

    public static T GetSetting<T>(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<T>(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<T>(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?

like image 25
Rico Suter Avatar answered Nov 01 '22 14:11

Rico Suter