我需要将哪些属性保存到RoamingSettings?

时间:2012-04-24 19:13:43

标签: c# windows-8 roaming

我需要将哪些属性保存到RoamingSettings?

与我序列化数据时一样,它需要DataContractDataMember属性。我可以将我的类序列化为XML,但我需要使用RoamingSettings保存它:

roamingSettings.Values["MyType"] = _mytype;

在调试时,我收到以下错误消息:

  

不支持此类型的数据   WinRT信息:尝试序列化要写入应用程序数据存储的值时出错

我想我需要一个属性,但是哪一个?

2 个答案:

答案 0 :(得分:4)

使用正确的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;
    }
}

示例调用

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

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

答案 1 :(得分:1)

处理这种情况的最佳方法是将对象序列化为字符串并存储它。

从存储的字符串值反序列化为目标对象。