51
votes

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.

14

14 Answers

34
votes

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.

17
votes

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 -

  1. In Team Explorer, right click on your Build Definition and choose Open Process File Location
  2. Double click on the XAML file that is selected
  3. In the designer, select the container called Sequence (this is the top-level container that goes around everything else).
  4. 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.
  5. Save and close the file.
  6. Check the file back in to TFS and try your build again.
11
votes

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

10
votes

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>
7
votes

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"
4
votes

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:

  1. In Visual Studio, on the Project Properties page, on the Application tab, the "Target framework" was set to ".NET Framework 4.5.1";
  2. 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.

3
votes

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.

2
votes

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>
1
votes

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.)

1
votes

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

0
votes

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

0
votes

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

0
votes

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

-1
votes

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.