创建xml文件以存储数据本地c#并从该创建的文件中读取数据

时间:2014-12-07 16:56:05

标签: c# silverlight

我想将从网址获取的数据存储到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;
                }
            });
        }
    }

1 个答案:

答案 0 :(得分:0)

这看起来像是Windows商店应用程序的过程,Silverlight有一个不同的API。有关读取和写入Silverlight独立存储的信息,请参阅此post