我正在使用这种方法在我的应用程序中序列化和反序列化 ObservableCollections。
public static async void SaveToXmlAsync(string fileName, T classInstanceToSave)
{
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.ReplaceExisting))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, new XmlWriterSettings() { Indent = true }))
{
serializer.Serialize(xmlWriter, classInstanceToSave);
}
}
}
public static async System.Threading.Tasks.Task<T> LoadFromXmlAsync(string fileName)
{
try
{
var files = ApplicationData.Current.LocalFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName).GetResults();
var file = files.FirstOrDefault(f => f.Name == fileName);
// If the file exists, try and load it it's data.
if (file != null)
{
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(fileName))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
T data = (T)serializer.Deserialize(stream);
return data;
}
}
}
// Eat any exceptions unless debugging so that users don't see any errors.
catch
{
if (IsDebugging)
throw;
}
// We couldn't load the data, so just return a default instance of the class.
return default(T);
}
}
我在那个主题中找到了这个方法:点击我
而且我不知道如何读取保存的数据。如何将从反序列化器方法返回的任务转换为我的集合?我试过了,但它无法编译:
ObservableCollection<Product> collection = Toolkit<ObservableCollection<Product>>.LoadFromXmlAsync("list1.xml");