2

我正在尝试在 Win 8 Store 应用程序中序列化 ObservableCollection。我已经为 Windows Phone 8 应用程序完成了此操作,但我对如何在 Windows 8 中执行此操作有点迷茫。

我知道IsolatedStorageFile在 Windows 8 中不起作用。我正在使用StorageFile类来实现它,但是我不确定如何使用它:-(

这是我如何在 Windows Phone 8 应用程序中执行此操作的代码:

try
{
    DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<NewsByTag>));
    using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (isf.FileExists(sFileName))
           isf.DeleteFile(sFileName);

           using (var stream = isf.CreateFile(sFileName))
           {
                serializer.WriteObject(stream, data);
                stream.Close();
           }
    }
}

...这就是我在 Windows 8 Store 应用程序中尝试做的一个:

try
{
    DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<NewsByTag>));
    StorageFile sfFavourites = await localFolder.CreateFileAsync(sFileName);


    using (StorageStreamTransaction sfFav = await sfFavourites.OpenTransactedWriteAsync())
    {
        serializer.WriteObject(sessioinOutputStream.ToString(), data);
    }
}

此外,在 WP8 中,我正在序列化为 XML 文件。但是,对于 Windows 8,我不知道什么是最好的。XML 还是 JSON?

有没有人有一个很好的例子如何做到这一点?

任何帮助都会非常感激;-)

问候!

4

1 回答 1

2

你可以这样做 -

MemoryStream sessionData = new MemoryStream();
DataContractSerializer serializer = new 
            DataContractSerializer(typeof(ObservableCollection<NewsByTag>));
serializer.WriteObject(sessionData, data);


StorageFile file = await ApplicationData.Current.LocalFolder
                         .CreateFileAsync(sFileName);
using (Stream fileStream = await file.OpenStreamForWriteAsync())
{
    sessionData.Seek(0, SeekOrigin.Begin);
    await sessionData.CopyToAsync(fileStream);
    await fileStream.FlushAsync();
}

以这种方式反序列化 -

StorageFile file = await ApplicationData.Current.LocalFolder.
                           GetFileAsync(sFileName);
using (IInputStream inStream = await file.OpenSequentialReadAsync())
{
    DataContractSerializer serializer = 
            new DataContractSerializer(typeof(ObservableCollection<NewsByTag>));
    var data = (ObservableCollection<NewsByTag>)serializer
                     .ReadObject(inStream.AsStreamForRead());
}
于 2013-10-20T07:55:38.490 回答