如何将XDocument保存到Windows应用商店应用LocalFolder

时间:2014-01-07 00:22:22

标签: xml windows-runtime linq-to-xml

我正在创建一个Windows应用商店应用,可以读取和写入XML文件。数据驻留在名为“DataFile”的StorageFile中,我想将其存储在ApplicationData.Current.LocalFolder中。我在下面尝试的代码产生一个InvalidCastException:无法将'Windows.Storage.Streams.FileRandomAccessStream'强制转换为'System.IO.Stream'。这样做的正确方法是什么?我使用VB是因为XML文字,但C#解决方案没问题。

    Dim feedXml As XElement =
    <Feeds>
        <%= From f In Feeds
            Select <Feed>
                       <FeedUrl><%= f.Url %></FeedUrl>
                   </Feed> %>
    </Feeds>
    Dim xdoc As New XDocument
    xdoc.Add(feedXml)
    Dim app = TryCast(Application.Current, App)
    Using fileStream As Stream = Await app.DataFile.OpenAsync(FileAccessMode.ReadWrite)
        xdoc.Save(fileStream)
    End Using

1 个答案:

答案 0 :(得分:0)

您应该使用AsStream扩展方法将FileRandomAccessStream转换为Stream。在C#中它看起来像:

FileRandomAccessStream stream = (FileRandomAccessStream)await app.DataFile.OpenAsync(FileAccessMode.ReadWrite);
Stream fileStream = stream.AsStream();
xdoc.Save(fileStream)