3

In C#, while loading DLL from folder using the below code getting these below stack trace, when tried to get the types.

var assembly = Assembly.LoadFile(assemblyInfo.FullName); // assembly loads perfectly using the absolute path.
var types = assembly.GetTypes(); // this line throws the below stacktrace.

Stack trace:

System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.Assembly.GetTypes()

I also have checked existing solutions: Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.', Loading DLLs at runtime in C# (didn't work)

Md. Alim Ul Karim
  • 2,401
  • 2
  • 27
  • 36

2 Answers2

4

Solution to the problem was quite easy. It is just using a different method from the assembly. Instead of using LoadFile, we should use LoadFrom

So the below code solves the problem efficiently

var assembly = Assembly.LoadFrom(assemblyInfo.FullName); // loads perfectly, absolute path to dll
var types = assembly.GetTypes(); // loads perfectly.

There is no need to use GetExportedTypes. We can get all the types.

LoadFrom does auto reflection binding with other DLLs, however, loadfile doesn't do the same.

Which resolves that export issue.

Md. Alim Ul Karim
  • 2,401
  • 2
  • 27
  • 36
  • Woah, I'm glad I found this, thank you very much good Sir! – user3793935 Sep 24 '20 at 08:54
  • `LoadFile` and `LoadFrom` are totally different functions. So your solution does not explain what was the issue, just a 'luck' – Zoli Jun 01 '22 at 12:57
  • @Zoli LoadFile loads the contents of the assembly, whereas, LoadFrom loads the file (with dependencies as well - if found in the same dir) or you can LoadFrom does the auto binding using reflection for you where LoadFile doesn't – Md. Alim Ul Karim Jun 02 '22 at 13:08
3

Assembly.LoadFile only loads the contents of an assembly , But Assembly.LoadFrom loads an assembly file perfectly (and dependencies If there are).

AminRostami
  • 2,585
  • 3
  • 29
  • 45