将数据集合保存到本地文件夹

时间:2013-01-19 11:59:37

标签: c# .net windows-8

[DataContract]
class UserData
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public int phoneNumber { get; set; }

    [DataMember]
    public string Course { get; set; }
    [DataMember]
    public Uri Image { get; set; }
}

[DataContract]
class UserItems
{
    [DataMember]
    static ObservableCollection<UserData> _items = new ObservableCollection<UserData>();
    [DataMember]
    public static ObservableCollection<UserData> Items
    {
        get { return _items; }
    }

这是AppDataManager

class AppDataManager
{
    public static async Task SaveAsync<T>(T data, string fileName)
    {

        StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, 
            CreationCollisionOption.GenerateUniqueName);


        var stream = await file.OpenStreamForWriteAsync();
        var serializer = new DataContractSerializer(typeof(T));

        serializer.WriteObject(stream ,data);
        await stream.FlushAsync();
    }

    public static async Task<T> RestoreAsync<T>(string fileName)
    {
        try
        {
            var file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

            var instream = await file.OpenStreamForReadAsync();
            var serializer = new DataContractSerializer(typeof(T));
            return (T)serializer.ReadObject(instream);
        }
        catch (Exception)
        {
            return default(T);
        }
    }
}
}

我试图保存一个对象并且它有效,但该集合是我的问题,我正在使用的应用程序是每次输入数据时保存用户数据。

问题是:如何保存数据集合以及如何将其作为数据集合检索?

1 个答案:

答案 0 :(得分:0)

检查此链接,它是关于Windows Phone环境的,但我认为它也适用于您的情况:http://geekswithblogs.net/mikebmcl/archive/2010/12/29/datacontractserializer-type-is-not-serializable-because-it-is-not-public.aspx。使用_items属性来装饰您的DataMember私人会员可能是个问题。

如果不是这样,也许ObservableCollection<T>DataContractSerializer不能很好地匹配,那么您可以使用常规List<T>备份可观察集合并将该列表标记为DataMember