有许多文章(codeproject、blog1、blog2、forum)将 WinRT 库用于 Windows 8 中的 .Net Framework 控制台应用程序。
我在 Windows 10 中使用 UWP 进行了尝试。但未能成功。我努力编译没有错误,但它发生了 BadImageFormatException
在运行时。
这是我做的。
- 使用 .NET Framework 4.6.1 目标创建控制台应用程序。
- 编辑 .csproj 文件以添加
<TargetPlatformVersion>10.0</TargetPlatformVersion>
- 引用以下三个库。
- 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 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 设置为 true,但同样的错误发生了。
在我看来,这个异常是说 System.Runtime.WindowsRuntime
试图在内部加载一些依赖库,但我不知道它是什么。
最佳答案
这里是这里的工作步骤,注意你们之间的细微差别:
第 1 步:添加到 .csproj 文件
<PropertyGroup>
<TargetPlatformVersion>10.0</TargetPlatformVersion>
</PropertyGroup>
第 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)
它在桌面上不可用,only types referenced here are supported in desktop.
关于c# - 将 UWP 库加载到 .NET Framework 应用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34547285/