Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the assembly (System.Reflection.Assembly) for a given type in .Net?

In .Net, given a type name, is there a method that tells me in which assembly (instance of System.Reflection.Assembly) that type is defined?

I assume that my project already has a reference to that assembly, just need to know which one it is.

like image 785
Fabio de Miranda Avatar asked Jul 17 '09 01:07

Fabio de Miranda


People also ask

What is System reflection assembly?

Namespace: System.Reflection. Summary. Defines an Assembly, which is a reusable, versionable, and self-describing building block of a common language runtime application.

Which method returns currently loaded assembly in which the specified type is defined?

GetAssembly(Type) Method.

How do you get type objects from assemblies that are already loaded?

Use Type. GetType to get the Type objects from an assembly that is already loaded.

What is assembly GetExecutingAssembly ()?

Assembly property to get the currently executing assembly based on a type contained in that assembly. It also calls the GetExecutingAssembly method to show that it returns an Assembly object that represents the same assembly.


2 Answers

Assembly.GetAssembly assumes you have an instance of the type, and Type.GetType assumes you have the fully qualified type name which includes assembly name.

If you only have the base type name, you need to do something more like this:

public static String GetAssemblyNameContainingType(String typeName)  {     foreach (Assembly currentassembly in AppDomain.CurrentDomain.GetAssemblies())      {         Type t = currentassembly.GetType(typeName, false, true);         if (t != null) {return currentassembly.FullName;}     }      return "not found"; } 

This also assumes your type is declared in the root. You would need to provide the namespace or enclosing types in the name, or iterate in the same manner.

like image 170
jpj625 Avatar answered Oct 01 '22 22:10

jpj625


Assembly.GetAssembly(typeof(System.Int32)) 

Replace System.Int32 with whatever type you happen to need. Because it accepts a Type parameter, you can do just about anything this way, for instance:

string GetAssemblyLocationOfObject(object o) {     return Assembly.GetAssembly(o.GetType()).Location; } 
like image 21
Matthew Scharley Avatar answered Oct 01 '22 20:10

Matthew Scharley