views:

33

answers:

2

I would like to access type information from a referenced (it is a project reference) assembly. The hard way would be to resolve the assembly's file path using VS solution, and load the assembly from file, but I'm sure that since the referenced assembly is already resolved/loaded in the executing assembly, there must be a much easier way, but that way really escapes me. How can I do this?

Example, in my MainAssembly, I reference LibAssembly. Now, in code in MainAssembly, I need to iterate members of types that are defined in LibAssembly.

+2  A: 

The easiest way I know is to use reflection. If you have a class called MyClass defined within LibAssembly, from your main assembly you could call code like the following:

Type[] types = Assembly.GetAssembly(typeof(MyClass)).GetTypes();

This would get you all of the types within LibAssembly.

Edit:

If you didn't know any of the types beforehand and could assume that the library would be in the same physical location as the executable, maybe something along the following lines would work:

using System;
using System.IO;
using System.Reflection;

string libraryFileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "myLib.dll");
Assembly assembly = Assembly.LoadFrom(libraryFileName);
Type[] myTypes = assembly.GetTypes();
nukefusion
`Type[] types = typeof(MyClass).Assembly.GetTypes();`
Tim Robinson
My problem is that I don't necessarily know of any one type in LibAssembly.
ProfK
Ok I see, I've updated my answer with a possible solution.
nukefusion
+3  A: 

To get a list of all loaded assemblies you can try to ask the appdomain:

AppDomain MyDomain = AppDomain.CurrentDomain;
Assembly[] AssembliesLoaded = MyDomain.GetAssemblies();
foreach (Assembly MyAssembly in AssembliesLoaded)
{
   //
}

Then you can go through all loaded assemblies and get their types by reflection.

schoetbi
This approach works, with one problem: The assembly I need to get types from isn't loaded until I instantiate a type from that assembly. This is sort of a Catch-22, because I'm trying to find out what types are in that assembly.
ProfK