我想将从网址获取的数据存储到xml文件中,并在没有互联网时显示该数据。
我有这个:
async Task CreateSaveFile()
{
// Create document
XDocument xmlDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Objects", from test in TestList
select new XElement("test",
new XElement("name", test.Name),
new XElement("number", test.Number))));
// Storage Folder
StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
string fileName = "test.xml";
StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
Stream stream = await file.OpenStreamForWriteAsync();
// Write file
xmlDocument.Save(stream);
stream.Flush();
}
这种方法可以将创建的test.xml中的数据导入列表:
private List<Test> testList = new List<Test>();
async Task<List<Test>> getTestList()
{
StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
foreach (StorageFile file in files)
{
// Get xml files
XDocument xmlFile = XDocument.Load(file.Path);
// Get TestObjects
testList = (from element in xmlFile.Root.Descendants("test")
select new Player(
element.Element("name").Value,
element.Element("number").Value)).ToList<Test>();
}
return testList;
}
我收到此错误类型&#39; System.Reflection.TargetInvocationException&#39;的未处理异常发生在System.Windows.ni.dll
中 public RelayCommand LoadedCommand
{
get
{
return new RelayCommand(async () =>
{
await CreateSaveFile();
try
{
TestList = await getTestList();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString()); throw;
}
});
}
}