JosephStyons
JosephStyons

Reputation: 58685

How can I get a list of types from a DLL in C#?

I'd like to point a C# application at a DLL and get a list of the types defined in that DLL. What I have so far looks right on the surface, but is giving the error indicated below.

using System.Reflection;

...

static void Main(string[] args)
{
    Assembly SampleAssembly;
    SampleAssembly = Assembly.LoadFrom("C:\\MyAssembly.dll"); //error happens here

    foreach (Type tp in SampleAssembly.GetTypes())
    {
        Console.WriteLine(tp.Name);
    }
}

/*
This will give me:
Unable to load one or more of the requested types.
Retrieve the LoaderExceptions property for more information.

I wish it would give me something like this:
MyClass1
MyClass2
MyClass3
*/

Upvotes: 4

Views: 5099

Answers (2)

sdfa
sdfa

Reputation: 66

Use ReflectionOnlyLoad instead of a straight load to prevent the runtime from attempting to run any code in the target assembly

Upvotes: 5

Kirk Woll
Kirk Woll

Reputation: 77546

The ReflectionTypeLoadException is being thrown because one of your types is throwing an exception during static initialization. This can happen if the method/property/field signatures depend on a Type that is not available. I recommend you catch for that exception and inspect the contents of the exception's LoaderExceptions property as suggested.

Upvotes: 2

Related Questions