Ошибка при сборке решения “Невозможно загрузить файл или сборку “ХХХ” или один из зависимых от них компонентов. Была сделана попытка загрузить программу, имеющую неверный формат”.
By: Date: 22.02.2011 Categories: !RUS,C#,PROGRAMMING,TFS

При сборке решения

Error    1    Невозможно загрузить файл или сборку "file:///D:/SOURCES/bin/x86/RELEASE/ELA/ELA.DocumentImaging.dll" или один из зависимых от них компонентов. Была сделана попытка загрузить программу, имеющую неверный формат. Строка 304, позиция 5.    D:/SOURCES/ELA/ELA.ClientMainForm.resx    304    5    ELA.Client

по английски это выглядит примерно так

Error 1 Could not load file or assembly 'file:///c:/users//documents/visual studio 2010/Projects/WindowsFormsApplication5/ClassLibrary1/bin/x86/Debug/ClassLibrary1.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format. Line 174, position 5. c:\users\documents\visual studio 2010\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Form1.resx 174 5 WindowsFormsApplication5

Нашел статейку http://blogs.msdn.com/b/visualstudio/archive/2010/06/19/resgen-exe-error-an-attempt-was-made-to-load-a-program-with-an-incorrect-format.aspx основной смысл которой сводился к тому что некий процесс (наверное имелось ввиду — процесс сборки) пытается загрузить сборку на которую у него есть ссылка с отличающейся архитектурой.

В статье предлагаются 3 способоа обойти проблему. Самый первый, собирать с AnyCPU я попробовал, применил для  всего решения. Это не помогло.

Остальные два решения

Notes on Workarounds 2 and 3:Workarounds 2 and 3 apply specifically to the scenario where a project targeting .NET 3.5 has a .resx file that references a 32-bit assembly. There is currently no workaround for targeting 4.0 and trying to reference a 32-bit assembly from 64-bit MSBuild or vice versa – aside from changing to use the MSBuild.exe of the architecture you’re targeting.Please be aware that by forcing ResGen.exe to execute as 32-bit, you are essentially introducing the opposite problem: ResGen.exe will now error if you try to load 64-bit architecture-specific reference assemblies in it.
Workaround 2:Make ResGen.exe 32-bit by:1. Cd “%ProgramFiles(x86)%Microsoft SDKsWindowsv7.0ABin”2. Corflags /32Bit+ /Force ResGen.exeHowever, since our current build process has a heuristic that assumes that ResGen.exe is MSIL, just doing the above step will cause a different error (“The specified task executable "ResGen.exe" could not be run. The handle is invalid”) unless you inform GenerateResource that ResGen.exe is now 32-bit via setting the property “ResGenToolArchitecture” to “Managed32Bit”. This can be accomplished by doing one of the following:

1. Adding <ResGenToolArchitecture>Managed32Bit</ResGenToolArchitecture> to a PropertyGroup in the project file of any project that generates resources targeting .NET 3.5 – since the corflags trick affects the bitness of ResGen.exe on a system-wide level, the property must be set for all affected projects as well.

2. OR If running MSBuild.exe directly, passing it using the global property switch: ‘/p:ResGenToolArchitecture=Managed32Bit’

3. OR Setting it as an environment variable in the command window that MSBuild.exe is run from or the VS 2010 IDE is opened from: ‘set RESGENTOOLARCHITECTURE=Managed32Bit’

Pros: Doesn’t require changing the architecture of the referenced assembly

Cons: More complicated; requires baking the workaround either into the project file, or into your build system as a whole.
Workaround 3:

Force the CLR to load all MSIL applications as 32-bit by:

1. Cd “%windir%\Microsoft.NET\Framework64\v2.0.50727”

2. Ldr64.exe setwow

Then, since this also is a way to force ResGen.exe to execute as though it’s a 32-bit process, you must also go through the second part of Workaround 2 (setting ResGenToolArchitecture=Managed32Bit).

Pros: Doesn’t require changing the architecture of the referenced assembly

Cons: Affects how the CLR works for the entire machine. Also the same cons as Workaround 2.

я не стал пробовать, т.к. возникли некоторые сомнения. Попытался разобраться с файлом ресурсов MainForm.resx, который вызывает ошибку. Декодировал ресурс из base64 в простой текст и увидел что в самом закодированном ресурсе стоит ссылка на сборку System.Windows.Forms, Version=4.0.0.0 и это при том что в свойствах самого проекта был задан Target Framework = 2.0.

(Примечание:При декодировании base64 столкнулся с проблемой).

Копаю дальше. Нашел баг на Microsoft Connect который гораздо ближе по смыслу чем первая найденная статья. Человек подтверждает догадки

Posted by DanyR on 28.10.2010 at 0:48
The patch from Ed Hartley has the following internal effect:

I decoded an ImageStream with «j00L» and «j0yL» and found out, that in VS2010 MS is serializing ImageLists with a reference to System.Windows.Forms, Version=4.0, even when the project is set to 2.0. The tip changes exactly this («0» to «y» changes «4» to «2»).

Please, please, please fix this ASAP.

Daniel

Там же к статье приложена программка для правки файлов ресурсов Set2010ImageListsToNET2.zip которая правит ссылку в ресурсном файле на System.Windows.Forms, Version=2.0.0.0.

Короче нужно те ресурсные файлы которые вызывают ошибку при сборке обработать этой прогой — это помогает.