How do you get the root namespace of an assembly?

Viewed 35652

Given an instance of System.Reflection.Assembly.

15 Answers

Not possible. Nothing specifies a "Root" namespace. The default namespace in the options is a visual studio thing, not a .net thing

There could be any number of namespaces in a given assembly, and nothing requires them to all start from a common root. The best you could do would be to reflect over all the types in an assembly and build up a list of unique namespaces contained therein.

Assemblies don't necessarily have a root namespace. Namespaces and Assemblies are orthogonal.

What you may be looking for instead, is to find a type within that Assembly, and then find out what its namespace is.

You should be able to accomplish this by using the GetExportedTypes() member and then using the Namespace property from one of the returned Type handles.

Again though, no guarantees all the types are in the same namespace (or even in the same namespace hierarchy).

Get Types gives you a list of Type objects defined in the assembly. That object has a namespace property. Remember that an assembly can have multiple namespaces.

Namespaces have nothing to do with assemblies - any mapping between a namespace and the classes in an assembly is purely due to a naming convention (or coincidence).

This solution works if you are trying to load an embedded resource.

var assembly = System.Reflection.Assembly.GetExecutingAssembly();
string[] resourceNames = assembly.GetManifestResourceNames();

string  resourceNameNoNamespace = $"Languages.{languageSupport.IsoCode}.Languages.xml";
var match = resourceNames.SingleOrDefault(rn => rn.EndsWith(resourceNameNoNamespace));
Dim applicationNamespace = TextBeforeFirst(Assembly.GetCallingAssembly().EntryPoint.DeclaringType.Namespace, ".")

Public Function TextBeforeFirst(value As String, expression As String) As String
  If String.IsNullOrEmpty(value) Or String.IsNullOrEmpty(expression) Then Return Nothing
  Dim index = value.IndexOf(expression)
  If index = -1 Then Return Nothing
  Dim length = index
  Return value.Substring(0, length)
End Function
Related