简体   繁体   中英

C# - Loading DLL Dynamic - System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types

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)

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.

Assembly.LoadFile只加载程序集的contents of an assembly ,但Assembly.LoadFrom完美地加载assembly file (如果有依赖项)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM