7

I want to get all of the types from my assembly, but I don't have the references, nor do I care about them. What does finding the interface types have to do with the references? and is there a way for me to get around this?

Assembly assembly = Assembly.LoadFrom(myAssemblyPath);
Type[] typeArray = assembly.GetTypes();

Throws: FileNotFoundException Could not load file or assembly 'Some referenced assembly' or one of its dependencies. The system cannot find the file specified.

Peter
  • 130
  • 3
  • 11

4 Answers4

5

Loading an assembly requires all of its dependencies to be loaded as well, since code from the assembly can be executed after it's loaded (it doesn't matter that you don't actually run anything but only reflect on it).

To load an assembly for the express purpose of reflecting on it, you need to load it into the reflection-only context with e.g. ReflectionOnlyLoadFrom. This does not require loading any referenced assemblies as well, but then you can't run code and reflection becomes a bit more awkward than what you 're used to at times.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • 7
    It sounds good but then I get this:Cannot resolve dependency to assembly 'refAssmbly' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event. I basically just want to look at it, so why do the references need to be resolved? – Peter Nov 10 '11 at 00:18
3

It seems to be a duplicate of Get Types defined in an assembly only, where the solution is:

public static Type[] GetTypesLoaded(Assembly assembly)
{
    Type[] types;
    try
    {
        types = assembly.GetTypes();
    }
    catch (ReflectionTypeLoadException e)
    {
        types = e.Types.Where(t => t != null).ToArray();
    }

    return types;    
}
Community
  • 1
  • 1
Shane Lu
  • 1,056
  • 1
  • 12
  • 21
0

An alternative to using the reflection only context might be Mono.Cecil by Jb Evain which is also available via NuGet.

ModuleDefinition module = ModuleDefinition.ReadModule(myAssemblyPath);
Collection<TypeDefinition> types = module.Types;
CodeFox
  • 3,321
  • 1
  • 29
  • 41
0

In order to load the assembly, it's necessary to load the assembly's dependencies. If, for example, your assembly contains a type that returns an XmlNode then you will have to load System.Xml.dll

phoog
  • 42,068
  • 6
  • 79
  • 117