1

I need to get all available classes in a giving namespace.

Here is what I have done

In my Index method in XyzController.cs I added this line.

var classesList = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == "PATH.TO.HAMESPACE").ToList()

Unfortunately, that gave me no records/classes.

However, when I created a new class in the the same namespace i.e. PATH.TO.HAMESPACE. with the same code. Then called this class from the controller, the code returns the correct classes list.

How can I run this code from the controller to get all available classes with in PATH.TO.HAMESPACE?

Junior
  • 11,602
  • 27
  • 106
  • 212

2 Answers2

1

Instead of GetExecutingAssembly() try GetAssembly(typeof(PATH.TO.HAMESPACE.SampleClass))

The problem is when you are in the controller the executing Assembly in not the same assembly of the classes you need, while when you created that class , the assemble is the correct one.

So you need to get the correct assembly and then filter it

Tarek Abo ELkheir
  • 1,311
  • 10
  • 13
0

Overkill method, but that could work:

AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.Namespace == "Namespace");

Or (and), you should try to load explicitly your assembly. With Assembly.Load or Assembly.LoadFrom.

Assembly.Load("your assembly fullname")
    .GetTypes()
    .Where(t => t.Namespace == "Namespace");
romain-aga
  • 1,441
  • 9
  • 14
  • The firs method you provided worked. How can I determine the full qualifying name for my assembly? – Junior Aug 19 '16 at 21:20
  • To get the assembly fullname, you can do that: `Type t = yourType` and copy this string: `t.Assembly.FullName`. If you reference the project in your csproj, you can find it in the project xml too. – romain-aga Aug 19 '16 at 21:24
  • Since you are able to get your types with my first method, instead of loading you could try the @TarekAboElkheir's method, that should work too. – romain-aga Aug 19 '16 at 21:29