Reputation: 31
This code does not return any namespaces, when called for System.Collections.
public static List<string> GetAssemblyNamespaces(AssemblyName asmName)
{
List<string> namespaces = new List<string>();
Assembly asm = Assembly.Load(asmName);
foreach (Type typ in asm.GetTypes())
if (typ.Namespace != null)
if (!namespaces.Contains(typ.Namespace))
namespaces.Add(typ.Namespace);
return namespaces;
}
Why is that? There are types in System.Collections. What can I do instead to get the namespaces?
Upvotes: 3
Views: 639
Reputation: 116138
Different assemblies may contain the same(or sub) namespaces. For ex A.dll
may contain the namespace A
and B.dll
may contain A.B
. So you have to load all assemblies to be able to find namespaces.
This may do the trick, but it still has the problem that namespace can be in a not-referenced, not-used assembly.
var assemblies = new List<AssemblyName>(Assembly.GetEntryAssembly().GetReferencedAssemblies());
assemblies.Add(Assembly.GetEntryAssembly().GetName());
var nss = assemblies.Select(name => Assembly.Load(name))
.SelectMany(asm => asm.GetTypes())
.Where(type=>type.Namespace!=null)
.Where(type=>type.Namespace.StartsWith("System.Collections"))
.Select(type=>type.Namespace)
.Distinct()
.ToList();
For example, If you run above code, you will not get System.Collections.MyCollections
since it is defined in my test code SO.exe
:)
Upvotes: 1
Reputation: 19262
var namespaces = assembly.GetTypes()
.Select(t => t.Namespace)
.Distinct();
by using LINQ
you can get the namespace of the assemly.
Upvotes: 0