Junior
Junior

Reputation: 11998

How can I search the assemblies for all the classes available in a specific namespace with from a controller using c#?

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?

Upvotes: 1

Views: 106

Answers (2)

Tarek Abo ELkheir
Tarek Abo ELkheir

Reputation: 1331

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

Upvotes: 1

romain-aga
romain-aga

Reputation: 1561

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");

Upvotes: 0

Related Questions