StorageFile NON Metro应用程序中的异步使用

时间:2012-05-03 09:18:49

标签: c# windows-8 windows-runtime isolatedstorage async-await

我正在尝试在我的类库中创建一个StorageFile实例...

var localFolder = ApplicationData.Current.LocalFolder;
StorageFile destinationFile = await localFolder.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName);

VS11没有建立说:'await'要求'Windows.Foundation.IAsyncOperation'类型具有合适的GetAwaiter方法。你错过了'系统'的使用指令吗?

显然我使用.net 4.5作为目标,我正在引用Windows程序集... 不知道为什么这个代码在MetroStyle中工作但不在类库中构建...如何在类库中创建一个Storagefile实例?在这个阶段,如果以异步方式创建文件并不重要......

请告诉我你的想法...... 斯泰利奥

4 个答案:

答案 0 :(得分:10)

对我有用的是“手动”添加TargetPlatformVersion

<PropertyGroup>
  <TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>

并在项目组中添加以下内容

<ItemGroup>
  <Reference Include="System.Runtime.WindowsRuntime" />
  <Reference Include="System.Runtime" />
  <Reference Include="Windows" />
</ItemGroup>

然后项目应该正常编译。

答案 1 :(得分:8)

我遇到了同样的问题。问题是名称空间标题中缺少系统命名空间。我只是在命名空间中包含系统并且它有效。希望它有所帮助。

答案 2 :(得分:5)

您似乎正在尝试使用WinRT库中的类型,因为StorageFile class documentation表示它仅适用于Metro,并且可以在Windows.Storage中找到。

This blog post介绍了如何构建它,但它似乎是一个手动过程。它还详细说明了错误的原因:

  

使用await关键字会使编译器查找GetAwaiter   此接口上的方法。因为IAsyncOperation没有   定义一个GetAwaiter方法,编译器想要查找   扩展方法。

基本上,您似乎需要添加对System.Runtime.WindowsRuntime.dll

的引用

请花时间阅读他的博客文章,但为了清楚起见,我将把重点放在这里。


以下毫不客气地剽窃的博客内容

首先,在记事本中,我在EnumDevices.cs中创建了以下C#源代码:

using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Foundation;

class App {
    static void Main() {
        EnumDevices().Wait();
    }

    private static async Task EnumDevices() {
        // To call DeviceInformation.FindAllAsync:
        // Reference Windows.Devices.Enumeration.winmd when building
        // Add the "using Windows.Devices.Enumeration;" directive (as shown above)
        foreach (DeviceInformation di in await DeviceInformation.FindAllAsync()) {
            Console.WriteLine(di.Name);
        }
    }
}

其次,我创建了一个Build.bat文件,我从开发人员命令提示符运行以构建此代码(这应该是1行,但我将它包装在这里以获取读取能力):

csc EnumDevices.cs  
/r:c:\Windows\System32\WinMetadata\Windows.Devices.Enumeration.winmd  
/r:c:\Windows\System32\WinMetadata\Windows.Foundation.winmd 
/r:System.Runtime.WindowsRuntime.dll  
/r:System.Threading.Tasks.dll

然后,在命令提示符下,我只运行EnumDevices.exe以查看输出。

答案 3 :(得分:1)

自从我发帖以来,这一定是很长的一段时间 添加参考后:
System.Runtime.WindowsRuntime.dll
System.Threading.Tasks.dll

并在项目文件中定位Windows 8:

  <PropertyGroup>
    <TargetPlatformVersion>8.0</TargetPlatformVersion>
  </PropertyGroup>

上面提到的例子可以在VS中编译。

相关问题