Is there any way to get the assembly that contains a class with name TestClass
?
I just know the class name, so I can't create an instance of that. And
Type objectType = assembly.GetType("TestClass");
didn't work for me.
You can use the Assembly property of a Type defined in that assembly to retrieve a reference to the Assembly object. The example provides an illustration. If you know the assembly's file system path, you can call the static (C#) or Shared (Visual Basic) AssemblyName.GetAssemblyName method to get the fully qualified assembly name.
The assembly in which the specified type is defined. type is null. The following example retrieves the assembly that contains the Int32 type and displays its name and file location. using System; using System.Reflection; public class Example2 { public static void Main() { // Get a Type object.
You can use code to output the information to the console or to a variable, or you can use the Ildasm.exe (IL Disassembler) to examine the assembly's metadata, which contains the fully qualified name. If the assembly is already loaded by the application, you can retrieve the value of the Assembly.FullName property to get the fully qualified name.
For those who are wondering, this throws System.IO.FileNotFoundException if the assembly could not be loaded. Assembly GetAssemblyByName (string name) { return AppDomain.CurrentDomain.GetAssemblies (). SingleOrDefault (assembly => assembly.GetName ().Name == name); } This will only work if the assembly in question is loaded.
Assembly asm = typeof(TestClass).Assembly;
will get you the assembly as long as it is referenced. Otherwise, you would have to use a fully qualified name:
Assembly asm = null;
Type type = Type.GetType("TestNamespace.TestClass, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
if (type != null)
{
asm = type.Assembly;
}
From the Type objectType
in the question, I assume you are actually after the type by name (not the assembly); so assuming the assembly is loaded and the type name is unique, LINQ may help:
Type objectType = (from asm in AppDomain.CurrentDomain.GetAssemblies()
from type in asm.GetTypes()
where type.IsClass && type.Name == "TestClass"
select type).Single();
object obj = Activator.CreateInstance(objectType);
However, it may be better to work with the assembly-qualified name instead of the type name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With