Assembly.GetTypes() throwing an exception

Viewed 17282

What does assembly GetTypes() do behind the scenes? Assuming an assembly has been loaded to the AppDomain does it still need to read from the physical DLL? And what the assembly manifest do?

Iterating through the assembly like this:

AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()) 

I'm occasionally getting the following error:

 Could not load file or assembly 

Which tells me that because an assembly is loaded into the AppDomain it's not necessarily fully loaded to memory. Sometimes it still needs to go back to the file.

My questions:

  1. Why is it doing that?
  2. What can I do to detect these semi-loaded assemblies?
3 Answers

This question is a bit old, but leaving a note here that GetTypes might throw an exception if the application has not loaded the assembly dependencies especially in the newer .NET Core/.NET 5/6 .dlls.

Microsoft has introduced{assemblyName}.deps.json file which contains dependencies for an assembly, so you will need to load those too before you can call GetTypes without getting an exception. I found these blog posts to be helpful on how to do that:

Related