ChatGPT解决这个技术问题 Extra ChatGPT

SGEN: An attempt was made to load an assembly with an incorrect format

I have a project that can build fine on my local machine, however, when I get TFS to build it, I receive the following error -

SGEN: An attempt was made to load an assembly with an incorrect format:

After reading through many other posts here on this topic, most people just say I need to change the build type to either x86 or Any CPU, rather than x64, but after trying countless combinations, this was not the solution. My program is also a windows service, so setting the App Pool to allow 32 bit applications (as suggested by others) is also not the solution.


D
Dave Oakley

I encountered this same issue today. A project would not build on my PC but built fine on other PC's

I eventually fixed it by doing the following:

Right-clicked the project with the error, went into Properties

Selected the Build tab and went to the last option which is "Generate serialization assembly" I set this to Off and the project now builds fine.


I ran my project - it worked fine. I ran it 10 minutes later and got this error - your solution worked for me - but what are the side effects of doing turning "Generate serialization assembly off"?
As far as I know, turning it On will speed up start up time, especially if you use [serializable] attributes, as the compiler will generate a serialization assembly at compile time if this setting is turned on. Essentially it invokes SGen to generate serialized assemblies in advance, which can then be deployed with the Application. This prevents the XmlSerializer having to generate these each time the application starts.
I set this to 'Auto' - and the project now builds fine! Thx!
D
David J

My problem was finally solved by this page - http://aplocher.wordpress.com/2012/10/12/sgen-an-attempt-was-made-to-load-an-assembly-with-an-incorrect-format-tfs-2010/

Just in case that page ever disappears in the future, here are the steps involved -

In Team Explorer, right click on your Build Definition and choose Open Process File Location Double click on the XAML file that is selected In the designer, select the container called Sequence (this is the top-level container that goes around everything else). In the Arguments list (typically at the bottom), change MSBuildPlatform from Microsoft.TeamFoundation.Build.Workflow.Activities.ToolPlatform.Auto to Microsoft.TeamFoundation.Build.Workflow.Activities.ToolPlatform.X86. Save and close the file. Check the file back in to TFS and try your build again.


Worked for me with an older solution and TFS2012. I ended up creating a legacy build template for the problematic solutions.
My debug build was fine, but my release build was broken (even though they were both using the same process file); doing this fixed it, thanks.
Thank you for including the steps involved; that WordPress blog is no longer available.
.NET Standard - I got this building Debug/AnyCPU with assembly that had "Generate serialization assembly = ON" and a reference to a standard assembly. When I changed it to "Auto" the error went away.
It has disappeared, unless you go wayback web.archive.org/web/20130208032854/http://…
L
Louis Somers

The problem disappears after installing the latest Windows SDK which includes the 64Bit version of sgen.exe:

http://msdn.microsoft.com/en-us/windows/desktop/bg162891.aspx

Sometimes (if that one does not help) the older version helps:

http://msdn.microsoft.com/en-us/windows/desktop/hh852363.aspx

For some reason the 64bit version of sgen is not included in the Microsoft Build Tools


This was the solution that worked for me when my batch file was failing after adding a x32 assembly.
Which component specifically do I need to install? The latest Windows SDK has 15 different components totaling 2.7GB. I'd rather only install the required component on all of my build servers. I tried installing just the .Net Framework 4.7.1 Software Development Kit, but still get the error :(
@deadlydog I have no idea which components are needed. Would be great if you could single it out and post the answer here.
O
Ola Eldøy

I found this issue relevant: https://github.com/dotnet/sdk/issues/1630

While waiting for this to be fixed in a future version, I was able to solve the problem by adding two targets to the csproj file, as suggested by https://github.com/joperezr:

<Target Name="RemoveDesignTimeFacadesBeforeSGen" BeforeTargets="GenerateSerializationAssemblies">
    <ItemGroup>
    <ReferencePath Remove="@(_DesignTimeFacadeAssemblies_Names->'%(OriginalIdentity)')" />
    </ItemGroup>
    <Message Importance="normal" Text="Removing DesignTimeFacades from ReferencePath before running SGen." />
</Target>

<Target Name="ReAddDesignTimeFacadesBeforeSGen" AfterTargets="GenerateSerializationAssemblies">
    <ItemGroup>
    <ReferencePath Include="@(_DesignTimeFacadeAssemblies_Names->'%(OriginalIdentity)')" />
    </ItemGroup>
    <Message Importance="normal" Text="Adding back DesignTimeFacades from ReferencePath now that SGen has run." />
</Target>

This is what fixed it for us (when Debug worked but Release didn't).
This worked for me when I built locally but when I ran on my build server this didn't fix the issue. However, I also added the SGenToolPath fix from @TDN (above) and it finally built correctly. So try this option as well!
using 4.7.2 having the targets in csproj and also using SGenToolPath did not work
Your answer really saved the day. I had to extend it a bit - stackoverflow.com/a/64474637/80002. In case someone faces the same problem.
T
TNV

I encountered the same error when I tried to compile my project (Platform target is set to x86) in Release. It compiled fine in Debug. I came to find out that in Release, Generate serialization assembly is run; hence, the call to the SGen utility. The problem was that MSBuild called the x64 version of SGen against my x86 EXE, which generated the error. I had to pass this MSBuild argument so that MSBuild uses the correct version of SGen:

/p:SGenToolPath="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools"

How did you know which version of SGEN was called?
I think I was able to see from the build output. Sorry, it's been awhile!
Ah yes, if you scroll up a bit, you can see it.
Thanks this was the most helpful answer for me. However I will point out that my release in TFS would not build on x86 so I changed my build definition to use x64. I know I added a new 32-bit dll to my solution. Do you know why it built with x64 and did not build with x86 with the SGEN error?
I have the opposite problem. My platform target is x64, but VS and MSBuild insist on using the x86 tools (like SGen).
J
Jon Schneider

In my case, this error was due not to an invalid combination of x86 / x64 settings, but due to trying to build a project targeting a specific .NET framework version (v4.5.1) whose reference assemblies had not been installed on the build server.

The combination of the following two conditions was responsible for the error:

In Visual Studio, on the Project Properties page, on the Application tab, the "Target framework" was set to ".NET Framework 4.5.1"; On the build server, in folder C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework, a folder named v4.5.1 was not present. (Other folders with version numbers, including v3.5, v4.0, and v4.5, were present.)

The fix was to install Windows Software Development Kit (SDK) for Windows 8.1 on the build server. In the install wizard, in the "Select the features you want to install" step, I unchecked all boxes except for the one for ".NET framework 4.5.1 Software Development Kit".

Running that install caused the missing v4.5.1 folder in the Reference Assemblies\Microsoft\Framework.NETFramework folder to be created, and the build to run successfully.


The same for me. I installed Microsoft Build Tools 2015. It fixed the reference assemblies and sgen issues.
T
Trevor Price

This question still pops up first in Google when I search certain keywords, so I'll post this in case anyone finds it relevant.

In my case, I had a project that built fine in "debug" but gave the OP's error in "release" mode. None of the solutions elsewhere in this thread solved the problem.

However, I ran into an obscure comment in another forum about web service references interfering with the build. A light bulb went off. My project had a number of legacy web service references that were no longer used. So I ripped them out. Lo and behold, I could now build the project in "release" mode, without disabling assembly serialization or fiddling with the CSPROJ or messing with SGEN references in Azure DevOps/VSTS.

Hopefully this saves someone time.


Not all heroes wear capes!
m
mark

My answer is an extension to that of ola-eldøy. In my case I had to exclude more assemblies, because each of them yielded the same dreadful error:

Could not load file or assembly bla-bla-bla 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)

Therefore my solution was to extend ola-eldøy's code and save it in Directory.Build.targets:

<Project>
  <ItemGroup>
    <ReflectionOnlyAssemblyNames Include="Microsoft.Bcl.AsyncInterfaces"/>
    <ReflectionOnlyAssemblyNames Include="System.Buffers"/>
    <ReflectionOnlyAssemblyNames Include="System.Numerics.Vectors"/>
    <ReflectionOnlyAssemblyNames Include="System.Runtime.CompilerServices.Unsafe"/>
  </ItemGroup>
  <Target Name="RemoveDesignTimeFacadesBeforeSGen" BeforeTargets="GenerateSerializationAssemblies">
    <ItemGroup>
      <_ReflectionOnlyAssembly_Names Include="@(_ReferencePath_Names)"
                                     Condition="'@(ReflectionOnlyAssemblyNames)' == '@(_ReferencePath_Names)' And '%(Identity)' != ''"/>
    </ItemGroup>
    <ItemGroup>
      <ReferencePath Remove="@(_DesignTimeFacadeAssemblies_Names->'%(OriginalIdentity)')" />
      <ReferencePath Remove="@(_ReflectionOnlyAssembly_Names->'%(OriginalIdentity)')" />
    </ItemGroup>
    <Message Importance="normal" Text="Removing DesignTimeFacades from ReferencePath before running SGen." />
  </Target>
  <Target Name="ReAddDesignTimeFacadesBeforeSGen" AfterTargets="GenerateSerializationAssemblies">
    <ItemGroup>
      <ReferencePath Include="@(_DesignTimeFacadeAssemblies_Names->'%(OriginalIdentity)')" />
      <ReferencePath Include="@(_ReflectionOnlyAssembly_Names->'%(OriginalIdentity)')" />
    </ItemGroup>
    <Message Importance="normal" Text="Adding back DesignTimeFacades from ReferencePath now that SGen has run." />
  </Target>
</Project>

C
CodeWhore

Per one of the comments in the accepted answer by @james-white the following worked for me:

Chagnge: GenerateSerializationAssemblies property in the project file from 'On' to 'Auto'

Wanted to pull this suggestion into an answer to make it more obvious to anyone just skimming through. Thank you James White


This magically worked for me. Thanks! But what the hell did I do?
K
Keith Robertson

I was having a similar problem, seeing the SGEN "incorrect format" error when building in VS or MSBuild from command line. My project is x64, but MSBuild insisted on using the 32-bit version of the tool. (Some of my peers work around this by building in VS 2015, but I have only VS 2017 installed and want to keep it that way.)

Looking at the diagnostic build output, it looks like SGEN is running from the directory named by its SdkToolsPath parameter (for me: C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\). This is assigned from TargetFrameworkSDKToolsDirectory. Looking at the targets files, this comes from SDK40ToolsPath. And that is set from MSBuild's .config file.

I resolved this by editing C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe.config (requires Admin privilege), setting the SDK40ToolsPath property using

<property name="SDK40ToolsPath" value="$([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\NETFXSDK\4.6.2\WinSDK-NetFx40Tools-x64', 'InstallationFolder', null, RegistryView.Registry32))" />

(Note: If you're looking for this path in the registry on a 64-bit OS, go to HKLM\SOFTWARE\WOW6432Node\Microsoft...)

The main change is, of course, x86 to x64 to use the 64-bit tools. I also changed the framework to be what we use (4.6.2). This may mean we can reliably only use tools for 64-bit projects and for this framework, with this change in place. Still, I hope this might help someone running into this issue. (I'm shocked and dismayed MSBuild doesn't automatically change the tools path based on Framework & Architecture.)


D
David Wiltcher

I had this same issue and viewing the output screen gave me more details. From that I found the Target Framework was higher than was allowed for this type of project (I was building a SQL Server CLR project). The target framework in the project was set to 4.0. Changing this back to 3.5 fixed the issue for me.

Dave


f
fedda

I upgraded a project from 4.0 to 4.5.2 and installed the Microsoft .NET Framework 4.5.2 Developer Pack on the build server. After that it worked. You have developer pack for all the other .net versions.

https://support.microsoft.com/en-us/help/2901951/the-microsoft--net-framework-4-5-2-developer-pack-for-windows-server-2


R
Rodolfo Gaspar

In my case, the solution compiled correctly in Debug, but there was a Release error in only one project.

Using this https://social.msdn.microsoft.com/Forums/en-US/13d3cc7a-88dc-476c-8a15-fa2d4c59e5aa/sgen-an-attempt-was-made-to-load-an-assembly-with-an-incorrect-format?forum=netfx64bit, I changed the project PlatformTarget who was with x86 problems for Any CPU.

I maintained the Solution with Mixed Platform and it was possible to compile in Release


S
Saeed Mousavi

This worked for me on Visual Studio 2017:

I changed one of my Project's Platform to x64 then I was getting this error while PUBLISH (Not Run)

If this is your case:

Go to Publish Settings Change Configuration Strictly from Any CPU to Release-x64 (or whatever)

Then the error while publish disappears.