我正在使用此方法在我的应用中序列化和反序列化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);
}
}
我在该主题中找到了这种方法:click me
我不知道如何阅读保存的数据。我如何将从反序列化器方法返回的Task转换为我的集合?我尝试过,但无法编译:
ObservableCollection<Product> collection = Toolkit<ObservableCollection<Product>>.LoadFromXmlAsync("list1.xml");
答案 0 :(得分:0)
ObservableCollection<Product> collection = await Toolkit<ObservableCollection<Product>>.LoadFromXmlAsync("list1.xml");
同时将 async 关键字添加到您自己的方法中。
祝你好运