System.BadImageFormatException 在 UWP 中与 WPF 桌面桥包

System.BadImageFormatException in UWP with WPF desktop bridge package

我已经完整详细地描述了本主题中的问题和问题System.NullReferenceException in AppServiceResponse and System.BadImageFormatException of UWP with WPF desktop bridge package,但仍然没有找到答案,是什么导致了这个失败。

主题 link 到 Windows 开发中心 上面描述了程序集,显示了所有使用过的代码和示例,包括修复问题的尝试和其他详细信息。所以我将只把任务的基本部分放在这个 Whosebug 主题中,以避免 post 中的文本过载,并且只关注 System.BadImageFormatException,这会引发 App.Connection Windows 应用程序包项目 中的空值,连接从 UWP WPF 应用程序,根据 UWP with Desktop Extension – Part 3 lesson 创建,(将请求发送到桌面扩展,读取注册表项值,并将请求从桌面扩展发送到 UWP,处理来自桌面代码的请求)。

我试过用不同的方法修复它(也在上面描述过),但找不到任何原因的线索,至少知道在哪里寻找问题,也许我错过了什么,但我不能'在互联网上的任何地方都找不到相关有用的答案

这是消息,但是 System.Runtime.WindowsRuntime.dll 已经在引用中:

System.BadImageFormatException HResult=0x80131058 Message=Could not load file or assembly 'System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=...' 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) Source=WpfApp1
StackTrace: at WpfApp1.MainWindow.d__4.MoveNext() in C:\Users\User\Desktop\UWP\App\WpfApp1\MainWindow.xaml.cs:line 58 at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine) at WpfApp1.MainWindow.InitializeAppServiceConnection() at WpfApp1.MainWindow..ctor() in C:\Users\User\Desktop\UWP\App\WpfApp1\MainWindow.xaml.cs:line 37 Inner Exception 1: BadImageFormatException: Cannot load a reference assembly for execution.

任何建议、指南或示例都会非常有帮助

编辑 1: ********************************* ****************************************************** *******************

我已经尝试了以下两种方式的所有组合 DebugRelease,以及更改解决方案平台“编译器设置”,从 VS 的菜单栏目标从“Any CPU”到“X86”,反之亦然,如 System.BadImageFormatException: Could not load file or assembly [duplicate] 所示,从 Solution->Properties->Configuration Properties->Configuration->Project contexts 以及从 Project->Properties->Build->Platform target,但是在所有情况下同样会出现功能和故障:

当前配置属性

Console Launcher - AnyCPU
UWP - x86
Package - x86
WPF - AnyCPU
WinForms - AnyCPU

将所有解决方案应用设置为 x86:

Console Launcher - x86
UWP - x86
Package - x86
WPF - x86
WinForms - x86

x64:

Console Launcher - x64
UWP - x64
Package - x64
WPF - x64
WinForms - x64

按场景执行相同的结果:

Lessons Part 1 "Run WinForms from UWP" and Part 2 "Passing parameters" 成功运行,运行s 应用程序发送参数并加载 WPFWinForms

来自 lesson Part 3 的场景同样失败,InitializeAppServiceConnection(); 抛出 System.BadImageFormatException 直接调试,尝试 运行 WPFWinForms 来自 UWP,对请求的应用程序不执行任何操作,仅显示 Console 启动器一秒钟,没有任何消息,然后 调用桌面代码读取注册码 抛出相同的 System.NullReferenceException

将所有应用程序设置为 AnyCPU,除了 UWP,其中 bin 调试输出路径,因为来自解决方案或应用程序属性的平台目标下拉菜单仅包含 x64, x86, ARM, ARM64:

Console Launcher - AnyCPU
UWP - x86 
Package - AnyCPU
WPF - AnyCPU
WinForms - AnyCPU

抛出:

Severity Code Description Project File Line Suppression State Error MSB3270 There was a mismatch between the processor architecture of the project being built "x86" and the processor architecture of the reference "C:\Users\User\Desktop\UWP_BD\UWP_BD\Launcher\bin\Debug\Launcher.exe", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project. Package C:\Program Files (x86)\Microsoft Visual Studio19\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets 2106

和:

Severity Code Description Project File Line Suppression State Warning The element 'PropertyGroup' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003' has invalid child element 'WapProjPath' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003'. List of possible elements expected: 'Property, VisualStudioVersion, MinimumVisualStudioVersion, AdditionalFileItemNames, AllowUnsafeBlocks, AppConfigForCompiler, ApplicationIcon, ApplicationRevision, ApplicationVersion, AppDesignerFolder, AspNetConfiguration, AspNetCoreHostingModel, AspNetCoreModuleName, AssemblyKeyContainerName, AssemblyKeyProviderName, AssemblyName, AssemblyOriginatorKeyFile, AssemblyOriginatorKeyFileType, AssemblyOriginatorKeyMode, AssemblyType, AutoGenerateBindingRedirects, AutorunEnabled, BaseAddress, BootstrapperComponentsLocation, BootstrapperComponentsUrl, BootstrapperEnabled, CharacterSet, CheckForOverflowUnderflow, CLRSupport, UseDebugLibraries, CodePage, Configuration, ConfigurationName, ConfigurationOverrideFile, CreateDesktopShortcut, CreateWebPageOnPublish, CurrentSolutionConfigurationContents, DebugSecurityZoneURL, DebugSymbols, DebugType, DefaultClientScript, DefaultHTMLPageLayout, DefaultTargetSchema, DefineConstants, DefineDebug, DefineTrace, DelaySign, DisableLangXtns, DisallowUrlActivation, CodeAnalysisAd.... Package C:\Users\User\Desktop\UWP_BD\UWP_BD\Package\Package.wapproj 49

x64:

Console Launcher - AnyCPU
UWP - x64 
Package - AnyCPU
WPF - AnyCPU
WinForms - AnyCPU

Severity Code Description Project File Line Suppression State Error MSB3270 There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\Users\User\Desktop\UWP_BD\UWP_BD\UWP_Control\bin\x64\Debug\UWP_Control.exe", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project. Package C:\Program Files (x86)\Microsoft Visual Studio19\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets 2106

我不确定,也许我应该将最低版本更改为周年纪念版Windows 10 (10.0; Build 10214) 创建 UWP 默认为 Windows 10 (10.0; Build 10586):

编辑 2: ********************************* ****************************************************** *******************

我将 Windows 10 Pro 64-bit OS, x64-basesd processorVisual Studio 2019 Version 16.1.4 一起使用,目标框架:.NET Framework 4.7.2 Version 4.7.03056Microsoft.NETCore.Universal Windows Platform 6.2.8 路径文件夹 C:\Program Files (x86)\Microsoft SDKs\Windows 包括文件夹:v7.0A , v8.1, v8.1A, v10.0A

.csproj中:

 <TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.14393.0</TargetPlatformVersion>
    <TargetPlatformMinVersion>10.0.14393.0</TargetPlatformMinVersion>
    <MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>

我遇到同样的失败System.BadImageFormatException,如果我将最低版本更改为Windows 10 周年纪念版(10.0;内部版本 14393) 目标版本 相同,之前和新的程序集都没有 Part 1 and Part 2 代码。

此外,我在System.NullReferenceException in AppServiceResponse and System.BadImageFormatException of UWP with WPF desktop bridge package Windows 开发中心“创建一个更简单的演示来重现问题”。因此,我仅根据 UWP with Desktop Extension – Part 3[=277] 使用 UWPWPF 创建了新包=] 与 UWP_FullTrust_3.

在之前的程序集中,我在 WPF 应用程序中错过了 SingleInstance.cs,但是将此代码包含到之前的或新的程序集中(没有“运行 app”和“传递参数”),抛出错误:

Severity Code Description Project File Line Suppression State Error CS0017 Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point. FullTrust C:\Users\User\Desktop\UWP_BD2\Solution1\FullTrust\SingleInstance.cs 57 Active

关于这部分代码:

[STAThread]
public static void Main(string[] args)
{
    SingleInstanceManager manager = new SingleInstanceManager();
    manager.Run(args);
} 

编辑 3: ********************************* ****************************************************** *******************

所以,Windows 10 Pro 64-bit OS, Version 1803 (OS Build 17134.829) 合适的目标版本应该是 17134,我不确定最低版本:

我刚刚在 Windows 几个小时前更新了。在目标菜单中创建 Windows Application Package Project 或不包含 17134UWP, 出现问题,对于更高版本,我收到此消息:

由于某种原因,目标选择菜单不包含 17134Windows Application Package Project 也没有了:

编辑 4: ********************************* ****************************************************** *******************

我已经安装了 SDK 版本 17134,并选择 17134 作为目标版本,Windows 应用程序包项目和 UWP 创建。

我添加了代码、参考、设置,但我遇到了同样的错误!我不确定我是否能够修复它。也许完整的测试项目,实际代码会有所帮助。

所以,这是一个完整的解决方案 repository UWP_desktop_bridge. It is UWP and Console Launcher to WPF, based on Part 1, Part 2, Part 3 of UWP-FullTrust lesson by Stefan Wick MSFT

没有 Part 1, Part 2 works, but with including InitializeAppServiceConnection(); to WPF InitializeComponent(); to get Part 3 功能的 InitializeAppServiceConnection(); 个场景,我得到:

System.BadImageFormatException HResult=0x80131058 Message=Could not load file or assembly 'System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=...' 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) Source=WpfApp1
StackTrace: at WpfApp1.MainWindow.d__4.MoveNext() in C:\Users\User\Desktop\UWP_desktop-bridge\Solution1\WpfApp1\MainWindow.xaml.cs:line 59 at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine) at WpfApp1.MainWindow.InitializeAppServiceConnection() at WpfApp1.MainWindow..ctor() in C:\Users\User\Desktop\UWP_desktop-bridge\Solution1\WpfApp1\MainWindow.xaml.cs:line 38 Inner Exception 1: BadImageFormatException: Cannot load a reference assembly for execution.

如果使用这部分代码,则与 SingleInstance.cs 相同:

[STAThread]
public static void Main(string[] args)
{
    SingleInstanceManager manager = new SingleInstanceManager();
    manager.Run(args);
}

Severity Code Description Project File Line Suppression State Error CS0017 Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.

它与我之前的项目中的功能和故障相似。

编辑 5:********************************* ****************************************************** *******************

此时,我精心创建了复制粘贴构建,基于ZhuMingHao/AppSerViceTest demo given in answer by Nico Zhu - MSFT on related question Send speech recognition args.Result as parameter in UWP desktop-bridge package:

调试加载 UWPWPF 成功。在 UWP AppSerViceTest/AppServiceTest/MainPage.xaml.cs:

中单击 Click 按钮

我遇到了同样的异常:

System.NullReferenceException: 'Object reference not set to an instance of an object.

点击 WPF Send Message 按钮,它只是关闭 WPF 应用程序,UWP StatusBlockInfoBlock 什么都不显示。

直接调试WPF点击Send message按钮,抛出相同System.BadImageFormatException:

的不同内容

System.BadImageFormatException HResult=0x80131058 Message=Could not load file or assembly 'System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=...' 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) Source=WpfApp1 StackTrace:
at WpfApp1.MainWindow.<Button_Click_1>d__5.MoveNext() in C:\Users\User\Desktop\UWP\UWP_DB_SR\WpfApp1\MainWindow.xaml.cs:line 91 at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine) at WpfApp1.MainWindow.Button_Click_1(Object sender, RoutedEventArgs e) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e) at System.Windows.Controls.Primitives.ButtonBase.OnClick() at System.Windows.Controls.Button.OnClick() at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e) at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent) at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e) at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted) at System.Windows.Input.InputManager.ProcessStagingArea() at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input) at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() at WpfApp1.App.Main() Inner Exception 1: BadImageFormatException: Cannot load a reference assembly for execution.

解决方案:************************************ ****************************************************** ***************

Stefan Wick MSFTSystem.BadImageFormatException 上 WDC 主题 System.NullReferenceException in AppServiceResponse and System.BadImageFormatException of UWP with WPF desktop bridge package 中描述的问题给出的解决方案特定的 UWP 桌面桥接应用程序通信项目,基于 UWP with Desktop Extension – 第 3 部分 示例 UWP-FullTrust/UWP_FullTrust_3 / 以及解决我的 Nico Zhu - MSFT 解决方案 ZhuMingHao/AppSerViceTest:

我的错误:

必须是正确的引用设置:

当从 non-UWP 项目(WPF、Winforms、控制台等)中错误地引用 Windows 运行时库时,会发生此异常。请务必按以下方式引用它们

  1. 在 "Add Reference …" 对话框中单击 "Browse …" 并将过滤器设置为 "All Files (*.*)"
  2. 导航到“%ProgramFiles(x86)%\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll”
  3. 导航到“%ProgramFiles(x86)%\Windows Kits\UnionMetadata\{TargetVersion}\Windows.winmd”