kuzditomi
kuzditomi

Reputation: 730

What attribute do I need to save to RoamingSettings?

What attribute do I need to save to RoamingSettings?

Like when I serialize my data, it needs a DataContract and DataMember attributes. I can serialize my class to XML, but I need to save it with RoamingSettings:

roamingSettings.Values["MyType"] = _mytype;

While debugging, I get this error message:

Data of this type is not supported.
WinRT information: Error trying to serialize the value to be written to the application data store

I guess I need an attribute, but which one?

Upvotes: 0

Views: 1213

Answers (2)

rob
rob

Reputation: 8400

Use the correct StorageFolder ApplicationData.Current.RoamingFolder

public static class RoamingStorage<T> {

    public static async void SaveData(string filename, T data)
    {
        try
        {
            StorageFile file = await ApplicationData.Current.RoamingFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(List<Item>));
                    serializer.WriteObject(outStream.AsStreamForWrite(), data);
                    await outStream.FlushAsync();
                }
            }
        }
        catch (Exception exc)
        {
            throw exc;
        }
    }

    public static async System.Threading.Tasks.Task<T> LoadData(string filename)
    {
        T data = default(T);
        try
        {
            StorageFile file = await ApplicationData.Current.RoamingFolder.GetFileAsync(filename);
            using (IInputStream inStream = await file.OpenSequentialReadAsync())
            {
               DataContractSerializer serializer = new DataContractSerializer(typeof(T));
               data = (T)serializer.ReadObject(inStream.AsStreamForRead());
            }
        }
        catch (FileNotFoundException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return data;
    }
}

example calling

RoamingStorage<List<Item>>.SaveData(FILENAME,Items);

List<Item> data = await RoamingStorage<List<Item>>.LoadData(FILENAME);

Upvotes: 4

Cinchoo
Cinchoo

Reputation: 6322

Best way to handle this situation, is to serialize the object into string and store it.

Deserialize from the stored string value into target object.

Upvotes: 1

Related Questions