Question

I have an application and a dll it depends upon, which, in their csproj files have been set to target .NET 3.5. We are trying to build these two projects to target .NET 4.0 by passing in /p:TargetFrameworkVersion=v4.0 as a command line parameter to msbuild (using NAnt). The build is succeeding, but running the program crashes immediately with a BadImageFormatException - "This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

Using .NET reflector, I have checked all references of the output exe and dll - everything references .NET 4.0 dlls; nothing references .NET 2; and yet my debugger is telling me that mscorlib 2.0.50727.4971 has been loaded.

Changing the projects themselves to target .NET 4, and then building in Visual Studio works fine - no issues.

I'm a bit stuck here, as I don't know what the next investigation step could be. I don't know why it is loading that version of mscorlib.

Was it helpful?

Solution

Check if the <supportedRuntime> element is present in your application's app.config. This must specify all versions of the Common Language Runtime the application supports. See http://msdn.microsoft.com/en-us/library/w4atty68.aspx for a full description of the <supportedRuntime> element.

In your case, since the application was previously targeting .NET 3.5, the app.config will most likely have an entry for "v2.0.50727" of the CLR, but I suspect there is not a corresponding entry for "v4.0".

As mentioned in the above article, if the entry is removed entirely, the version of the runtime used to build the application used. I believe it's recommended each supported version is explicitly specified in app.config.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top