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

有许多文章( codeproject , blog1 , blog2 , 论坛 )将WinRT库用于Windows 8中的.Net Framework控制台应用程序。

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

这就是我所做的。

  1. 使用.NET Framework 4.6.1目标创建控制台应用程序。
  2. 编辑.csproj文件以添加10.0
  3. 参考以下三个库。
    • c:\ Program Files(x86)\ Windows Kits \ 10 \ UnionMetadata \ Windows.winmd(显示Windows运行时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)

与Windows 8示例相反,引用System.Runtime.dll时出错。

代码如下。 请注意,该代码来自Microsoft论坛 。

 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显示not null 。 因此,调用库本身似乎很好。 但GetGeopositionAsync导致BadImageFormatException

exception消息详细信息如下。

抛出exception:mscorlib.dll中的“System.BadImageFormatException”

附加信息:无法加载文件或程序集’System.Runtime.WindowsRuntime,Version = 4.0.10.0,Culture = neutral,PublicKeyToken = b77a5c561934e089’或其依赖项之一。 不应加载引用程序集以执行。 它们只能在Reflection-only loader上下文中加载。 (HRESULTexception:0x80131058)

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

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

以下是在此处工作的步骤,请注意您之间的细微差别:

第1步 :添加到.csproj文件

   10.0  

第2步 :添加引用

 C:\Program Files (x86)\Windows Kits\10\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) 

它不能在桌面内使用, 只有桌面支持此类引用的类型。

我有这个错误,我将Microsoft.NETCore.UniversalWindowsPlatform的版本从“5.0.0”升级到“5.2.2”,我的程序开始工作