Blaxx
Blaxx

Reputation: 225

Get all namespaces from .dll

In a DLL (GUI) I need to get a List of all namespaces in the current Application (so for example if I would bind that DLL into a Project named "Hundekuchen", it should List

{ "GUI", "Hundekuchen" }

Is there any inbuilt function for this?

Upvotes: 3

Views: 8003

Answers (3)

jcvandan
jcvandan

Reputation: 14314

Look into the System.Reflection namespace, this is where you will find the functionality to retrieve information about assemblies.

This may not be exactly what you need but it shows the sort of things you can achieve, I am getting all the types in the currently executing assembly, iterates them and prints out the namespace of each type.

foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
    Console.WriteLine(t.Namespace);
}

Just inspect the Assembly class and you should find a way to solve your problem.

Upvotes: 1

Peter Wiles
Peter Wiles

Reputation: 406

You can get a list of all assemblies in the AppDomain, then all classes in all loaded assemblies, but you will have to filter out the ones you don't want to see because there are lots of assemblies linked in from mscorlib and the System libraries. Here's a quick and dirty one (using .NET 3.5) - you might need to filter out a few more if you link other libraries you don't want to see:

    var enumerable = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(assembly => assembly.GetTypes())
        .Select(type => type.Namespace)
        .Distinct()
        .Where(name => name != null &&
                       !name.StartsWith("System") &&
                       !name.StartsWith("Microsoft") &&
                       !name.StartsWith("MS.") &&
                       !name.StartsWith("<"));

Upvotes: 6

carlosfigueira
carlosfigueira

Reputation: 87228

No built-in function, but you can enumerate the types in the assembly, and get their namespaces.

        Assembly asm = typeof(MyApplication).Assembly;
        List<string> namespaces = new List<string>();
        foreach (var type in asm.GetTypes())
        {
            string ns = type.Namespace;
            if (!namespaces.Contains(ns))
            {
                namespaces.Add(ns);
            }
        }

        foreach (var ns in namespaces)
        {
            Console.WriteLine(ns);
        }

Upvotes: 11

Related Questions