Peter
Peter

Reputation: 130

Why does Assembly.GetTypes() require references?

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.

Upvotes: 7

Views: 3526

Answers (4)

CodeFox
CodeFox

Reputation: 3502

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;

Upvotes: 0

Shane Lu
Shane Lu

Reputation: 1104

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;    
}

Upvotes: 3

Jon
Jon

Reputation: 437386

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.

Upvotes: 5

phoog
phoog

Reputation: 43046

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

Upvotes: 0

Related Questions