将 UWP 库加载到 .NET Framework 应用中

Load UWP library into .NET Framework app

在 Windows 8.

中有许多文章 (codeproject, blog1, blog2, forum) 将 WinRT 库用于 .Net Framework 控制台应用程序

我在 Windows 10 中用 UWP 尝试过。但未能成功。我努力编译没有错误,但它发生在运行时BadImageFormatException

这就是我所做的。

  1. 使用 .NET Framework 4.6.1 目标创建控制台应用程序。
  2. 编辑 .csproj 文件以添加 <TargetPlatformVersion>10.0</TargetPlatformVersion>
  3. 引用三个库如下。
    • c:\Program Files (x86)\Windows Kits\UnionMetadata\Windows.winmd(显示 Windows Runtime 1.4)
    • c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll(显示 4.0.10.0)
    • c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5.1\System.Runtime.InteropServices.WindowsRuntime.dll(显示 4.0.0.0)

与Windows8例相反,引用System.Runtime.dll时出错

代码如下。请注意,代码来自 Microsoft forum.

class Program
{
    static void Main(string[] args)
    {

        Geolocator locator = new Geolocator();
        var status = Geolocator.RequestAccessAsync();

        if (status != null)
        {
            Console.WriteLine("not null");
            Task.Run(async () =>
            {
                Geoposition pos = await locator.GetGeopositionAsync();
                Console.WriteLine(pos.Coordinate.Accuracy);
            });
        }
        else
        {
            Console.WriteLine("null");
        }
        Console.ReadLine();
    }

编译成功,控制台显示not null。因此,库本身的调用似乎很好。但是 GetGeopositionAsync 导致 BadImageFormatException.

异常消息详情如下。

Exception thrown: 'System.BadImageFormatException' in mscorlib.dll

Additional information: Could not load file or assembly 'System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)

我已经尝试 (1) 将构建配置更改为 x86/x64/AnyCPU (2) 并将 Copy Local 设置为对所有引用都是正确的,但发生了同样的错误。

在我看来,这个异常是说 System.Runtime.WindowsRuntime 试图在内部加载一些依赖库,但我不知道它是什么。

这里是工作的步骤,注意你的之间的细微差别:

步骤 1:添加到 .csproj 文件

  <PropertyGroup>
    <TargetPlatformVersion>10.0</TargetPlatformVersion>
  </PropertyGroup>

步骤 2:添加对

的引用
C:\Program Files (x86)\Windows Kits\UnionMetadata\Windows.winmd

步骤 3:添加对

的引用
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll

注意差异,v4.5 而不是 v4.5.1,并且没有引用 System.Runtime.InteropServices.WindowsRuntime.dll

这在这里工作正常(Win10,VS2015)。

旁注,无论如何调用 Geolocator 都会失败:

This operation is only valid in the context of an app container. (Exception from HRESULT: 0x8007109A)

它不能在桌面上使用,only types referenced here are supported in desktop.

我遇到了这个错误,我将 Microsoft.NETCore.UniversalWindowsPlatform 的版本从“5.0.0”升级到“5.2.2”,我的程序开始运行