Loading a .NET 3.5 assembly via reflection in .NET 2.0

1.1k views Asked by At

I have an interesting situation and am trying to do something that I'm not even sure is possible.

I have a .NET 2.0 project that via reflection loads an assembly, and calls a specific method on that assembly. We are looking at moving forward and starting to use .NET 3.5 in the environment, but want to minimize risk with regard to this "host" application. Therefore we were trying to load the .NET 3.5 assembly from the .NET 2.0 project, since 3.5 is an extension of the 2.0 framework, etc.

Well, in doing this we get the following error:

The format of the file 'MyDllNameHere.DLL' is invalid

So, from the looks of this it isn't possible. Can anyone confirm this? Is there a workaround?

Then a second question, if it isn't possible, can we recompile the host under .NET 3.5 and then have it load .NET 2.0 assemblies via reflection?

3

There are 3 answers

1
Jerod Venema On

You can't load 3.5 assemblies in 2.0, because they may reference stuff that didn't exist in the 2.0 framework.

You can do the reverse like you mentioned though, 3.5 should load 2.0 assemblies with no problems.

1
Hans Passant On

That's not possible, the assembly format hasn't changed between 2.0 and 3.5. .NET 3.5 uses the exact same CLR version and assembly metadata format. The only difference between the versions is a new set of assemblies, notably those that support WPF, WCF and Linq. Trying to load a 3.5 assembly that references types from those new assemblies produces a very different error message. It will complain that it can't find the 3.5 assembly.

You would get an exception like this when you are actually running the .NET 1.x version of the CLR, the 2.0 assembly format did change. Also, although it isn't a good match for the exception message, you'll get an exception complaining about the assembly format if your code is running on the 64-bit version of the framework and you're trying to load an assembly that contains 32-bit native code. Or the other way around.

1
Mitchel Sellers On

Well, I wanted to post a more detailed answer to this here since I have since found out some more details. First of all special thanks to nobugs as he pointed me to the proper starting point for the issue.

First of all, nobugs was correct, the error message that I was encountering was NOT a proper error message. My code was incorrectly being called by a 1.1 host application and not that of a 2.0 host application.

As soon as I switched to a 2.0 host application, that is when the true magic started. From my 2.0 application, which simply loads a class via reflection and executes a specific method, I was able to successfully instantiate and execute a method that was contained inside of a .NET 3.5 assembly, that was using LINQ.

Works flawlessly!