写/恢复ObservableCollection <t> </t>

时间:2013-11-03 12:49:04

标签: c# .net windows-phone isolatedstorage datacontractserializer

我将ObservableCollection保存并恢复到IsolatedData存在很大问题。 我正在尝试使用此代码。

Observable的助手类

public class ListItem {
    public String Title { get; set; }
    public bool Checked { get; set; }

    public ListItem(String title, bool isChecked=false) {
        Title = title;
        Checked = isChecked;
    }
    private ListItem() { }

}

IsoHelper

public class IsoStoreHelper {
    private static IsolatedStorageFile _isoStore;
    public static IsolatedStorageFile IsoStore {
        get { return _isoStore ?? (_isoStore = IsolatedStorageFile.GetUserStoreForApplication()); }
    }

    public static void SaveList<T>(string folderName, string dataName, ObservableCollection<T> dataList) where T : class {
        if (!IsoStore.DirectoryExists(folderName)) {
            IsoStore.CreateDirectory(folderName);
        }

        if (IsoStore.FileExists(folderName + "\\" + dataName+".dat")) {
            IsoStore.DeleteFile(folderName + "\\" + dataName + ".dat");
        }

        string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
        try {
            using (var stream = new IsolatedStorageFileStream(fileStreamName, FileMode.Create, IsoStore)) {
                var dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
                dcs.WriteObject(stream, dataList);
            }
        } catch (Exception e) {
            Debug.WriteLine(e.Message);
        }
    }

    public static ObservableCollection<T> LoadList<T>(string folderName, string dataName) where T : class {
        var retval = new ObservableCollection<T>();

        if (!IsoStore.DirectoryExists(folderName) || !IsoStore.FileExists(folderName + "\\" + dataName + ".dat")) {
            return retval;
        }

        string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);

        var isf = IsoStore;
        try {
            var fileStream = IsoStore.OpenFile(fileStreamName, FileMode.OpenOrCreate);
            if (fileStream.Length > 0) {
                var dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
                retval = dcs.ReadObject(fileStream) as ObservableCollection<T>;
            }
        } catch {
            retval = new ObservableCollection<T>();
        }

        return retval;
    }
}

而我正试图以这种方式使用它

public partial class MainPage : PhoneApplicationPage{
    public ObservableCollection<ListItem> ListItems = new ObservableCollection<ListItem>();
    bool isListSaved;
    private void Panorama_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
        if (strTag.Equals("list") ) {
                isListSave = false;
                ListItems = IsoStoreHelper.LoadList<ListItem>("settings", "ListItems");
        } else if (!isListSave) {

                IsoStoreHelper.SaveList<ListItem>("settings", "ListItems", ListItems);
        }
    }
}

当我尝试在第A first chance exception of type 'System.Security.SecurityException' occurred in System.Runtime.Serialization.ni.dll行读取保存的文件时,我不断获得ReadObject(fileStream),但FileAccess看起来很好。

任何结论都将受到赞赏。


解决:

就像Dmytro Tsiniavskyi说我完全忘记了ListItem中的[DataContract]和[DataMember]。更重要的是,我找到了更好的保存和加载数据的解决方案。我最终得到了ListItem的这段代码

[DataContract]
public class ListItem {
    [DataMember]
    public String Title { get; set; }
    [DataMember]
    public bool Checked { get; set; }

    public ListItem(String title, bool isChecked=false) {
        Title = title;
        Checked = isChecked;
    }
    private ListItem() { }

}

此代码用于保存/加载收集,该代码最初创建here并修改了一点点以便更好地使用。

public partial class IsolatedRW {
    public static void SaveData<T>(string fileName, T dataToSave) {
        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
            try {

                if (store.FileExists(fileName)) {
                    store.DeleteFile(fileName);
                }

                if (!store.DirectoryExists("Settings")) store.CreateDirectory("Settings");
                IsolatedStorageFileStream stream;
                using (stream = store.OpenFile("Settings/"+fileName+".xml", System.IO.FileMode.Create, System.IO.FileAccess.Write)) {
                    var serializer = new DataContractSerializer(typeof(T));
                    serializer.WriteObject(stream, dataToSave);
                }
                stream.Close();
            } catch (System.Security.SecurityException e) {
                //MessageBox.Show(e.Message);
                return;
            }
            Debug.WriteLine(store.FileExists("Settings/" + fileName + ".xml"));
        }
    }

    public static T ReadData<T>(string fileName) {
        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {

            Debug.WriteLine(store.FileExists("Settings/" + fileName + ".xml"));
            if (store.FileExists("Settings/" + fileName + ".xml")) {
                IsolatedStorageFileStream stream;
                using (stream = store.OpenFile("Settings/"+fileName+".xml", FileMode.OpenOrCreate, FileAccess.Read)) {

                    try {
                        var serializer = new DataContractSerializer(typeof(T));
                        return (T)serializer.ReadObject(stream);

                    } catch (Exception) {
                        return default(T);
                    }
                }
                stream.Close();
            }
            return default(T);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

尝试为[DataContract]课程添加ListItem属性。

[DataContract]
public class ListItem {

    [DataMember]
    public String Title { get; set; }

    [DataMember]
    public bool Checked { get; set; }

    public ListItem(String title, bool isChecked=false) {
        Title = title;
        Checked = isChecked;
    }

    private ListItem() { }
}