How to get a list of classes in .NET.

I tried Assembly.ReflectionOnlyLoadFrom(@"path\System.Core.dll") and ReflectionOnlyLoad, but I have exceptions and errors. How to get all namespaces / classes in an assembly correctly?

For example, I got this exception.

 Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. 
+2
source share
3 answers

If you can reference System.Core, then

  List<string> namespaces = new List<string>(); var refs = Assembly.GetExecutingAssembly().GetReferencedAssemblies(); foreach (var rf in refs) { if (rf.Name == "System.Core") { var ass = Assembly.Load(rf); foreach (var tp in ass.GetTypes()) { if (!namespaces.Contains(tp.Namespace)) { namespaces.Add(tp.Namespace); Console.WriteLine(tp.Namespace); } } } } 

If you cannot, you will need to attach to the AssemblyResolve CurrentDomain event and load all the type assemblies that System.Core.dll uses when loading the dll.

+2
source

To load an assembly and then get a list of all types:

 Assembly assembly = Assembly.ReflectionOnlyLoadFrom("System.Core.dll"); Type[] types = assembly.GetTypes(); 

Unfortunately, this will throw an exception if any of the open types cannot be loaded, and sometimes this load failure cannot be avoided. In this case, however, the thrown exception contains a list of all types that were loaded successfully, and therefore we can simply do this:

 Assembly assembly = Assembly.ReflectionOnlyLoadFrom("System.Core.dll"); Type[] types; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { types = ex.Types; } 

This will give you a list of all types, including interfaces, structures, enumerations, etc. (if you only need classes, you can filter this list).

+3
source

Here is your answer to your question. I don’t need to copy and paste it here for you, it can be a greener to save space, and not copy the code from another thread. :-)

+1
source

All Articles