3

I have created a WinForms UserControl.

When I leave the platform at AnyCPU, I can debug it without any problem: When I press Play, the preview comes up.

Then I try to change the project to x86. Therefore I click "AnyCPU", then "Configuration Manager".

At "Active project platform", I select "New...".

Now I select "x86" and click "Ok".

Then, when I click "Play", I get the error "System.BadImageFormatException".

Is that a common problem, or something very, very wrong on my system?

It happens each time I try this with a new project.

enter image description here

enter image description here

enter image description here

tmighty
  • 10,734
  • 21
  • 104
  • 218
  • did you added some references in your project? If so check that you are not using x64 dlls as references – Hadi Apr 21 '19 at 20:25

2 Answers2

3

I can reproduce the error you find in VS 2017 15.9.8 just by:

  • Create new (VB or C#) Windows Forms Control Library
  • Check it runs via default AnyCpu solution platform
  • Create new x86 solution platform
  • Try and run the project

When you debug a WindowsFormsControlLibrary in Visual Studio, your DLL is loaded via debug host "UserControlTestContainer.exe" which is built for 'AnyCpu (64 bit preferred)'.

You can find details of this by right clicking the running debug host's task bar, right clicking on its icon, select Properties to find its path, and passing to e.g. ILSpy.

So I think that when the debug host runs as 64 bit, and is passed a 32 bit dll to load, the mismatch in bitness causes Assembly.LoadFrom to fail.

[Edit]

This does seem to be a bug as it prevents (easily) debugging a WinForms control library that has a dependency (e.g. unmanaged code) that is x86 only.

But I doubt that WinForms debugging problems for x86 only are something the VS team would prioritise.

As a workaround you can write your own test container (!) or:

  • Start the VS command prompt as admin
  • Make a copy of UserControlTestContainer.exe
  • Use corflags /32bitreq+ /32bitpref+ <PathToExe> to set the copy to run as x86
  • Set the copy as the "Start external program" target in debug options
  • Set the path to your dll as the debug command line argument
Peter Wishart
  • 11,600
  • 1
  • 26
  • 45
  • Thank you. Do you think that's a bug (or let's say a major user-unfriendliness) that the VS team should tackle? Am I actually the only one who ever discovered this behaviour? I haven't found any other reports or solutions so far. – tmighty Apr 23 '19 at 22:03
  • Thank you very much for your indepth answer!! Really helpful! – tmighty Apr 25 '19 at 13:11
-1

This is a common problem that usually means that you are trying to call 64-bit library from 32-bit executable. Make sure you are using 32-bit libraries when you compile for x86.

Vasya
  • 469
  • 2
  • 6