创建一个 xml 文件以在本地存储数据 C# 并从该创建的文件读取数据
本文关键字:文件 数据 创建 存储 读取 一个 xml | 更新日期: 2023-09-27 18:33:36
我想将从URL获得的数据存储到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();
}
而这个方法从创建的测试中获取数据.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;
}
我收到此错误 System.Windows.ni 中发生了类型为"System.Reflection.TargetInvocationException"的未处理异常.dll
public RelayCommand LoadedCommand
{
get
{
return new RelayCommand(async () =>
{
await CreateSaveFile();
try
{
TestList = await getTestList();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString()); throw;
}
});
}
}
这看起来像Windows应用商店应用程序的过程,Silverlight有一个不同的API。请参阅这篇文章,了解如何读取和写入 Silverlight 独立存储。