Windows 8 Metro App开发[6]访问Assets文件夹

Windows.Storage名称空间

我们首先需要认识一下Windows.Store名称空间。

    如果你去阅读微软MSDN上提供的文档Windows.Storage文档你会发现里面有一个StorageFolder类,通过该类,我们可以操作文件夹和相关的内容。StorageFolder类有一个方法叫做StorageFolder.CreateFileAsync,这个方法会在当前文件夹中异步的创建一个文件。同时,你也会看到,这里有获取文件内容,读取文件属性等方法。

操作代码如下:

 

   async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            StorageFolder InstalltionFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            string CountriesFile = @"Assets\output.xml";
            StorageFile file = await InstalltionFolder.GetFileAsync(CountriesFile);

            Stream countries = await file.OpenStreamForReadAsync();

            XDocument doc = XDocument.Load(countries);
       
        }

本地XML文件:

 

<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book category="CHLDREN">
  <title>Harry Potter</title>
  <author>JK. Rowling</author>
  <year>2005</year>
  <price>39.95</price>
</book>
<book category="WEB">
  <title>Harry Potter</title>
  <author>JK. Rowling</author>
  <year>2005</year>
  <price>39.95</price>
</book>
</bookstore>

 

这里需要特别注意的是asyncawait两个关键字,这两个是C#中新的关键字,在这里我们只需要知道在调用异步函数的时候需要使用到,后续的学习系列中我会对async和await进行详细的讲解。

运行效果:

 

 

 

posted @ 2013-02-07 10:32  NSDefaultRunLoopMode  阅读(321)  评论(0编辑  收藏  举报