views:

81

answers:

2

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
*/
+2  A: 

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.

Kirk Woll
Are you sure about that? I thought the static initialization only takes place when the class is first used.
ChaosPandion
@ChaosPandion is right, I tried it. Reflection let me list all the types and all their members without executing the static initializer. Only when I try to instantiate a type, does the initializer kick in and throw.
Timwi
That's what I get for working from memory. I thought that was the case, but nice catch. Answer edited.
Kirk Woll
This explains why the answer given by sdfa works...
JosephStyons
+3  A: 

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

sdfa