我正在尝试在Win 8商店应用程序中序列化ObservableCollection。我已经为Windows Phone 8应用程序做了这个,但我在Windows 8中如何做到这一点有点迷失。
我知道 IsolatedStorageFile 在Windows 8中不起作用。我正在使用 StorageFile 类来实现它,但是我不知道如何使用它: - (
以下是我在Windows Phone 8 App中如何做到的代码:
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商店应用中尝试做的那个:
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?
有没有人有一个很好的例子怎么做?
任何帮助都非常适合; - )
问候!
答案 0 :(得分: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());
}