Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly.GetType is returning null

Tags:

c#

reflection

I am trying to dynamically load an encryption assembly but my GetType is returning null, even though I am using the correct class name. Here's the code:

//Load encryption assembly.
Assembly encryptionAssembly = Assembly.LoadFrom("Encryption.dll");
foreach(Type t in encryptionAssembly.GetTypes())
   {
      MessageBox.Show(t.Name.ToString());
      // This shows "Encryption"
   }
Type encryptionClass = encryptionAssembly.GetType("Encryption");
// But this returns null

I've got a bit of a headache with this one. The class is public and I've definitely spelled it correctly.

Thanks in advance.

like image 301
Ste Avatar asked May 28 '12 10:05

Ste


4 Answers

Here

MessageBox.Show(t.FullName.ToString()); //FULLNAME

print out the FullName of the type and after use that FullName to get the type from the assembly.

like image 150
Tigran Avatar answered Nov 02 '22 08:11

Tigran


I didn't know the the fully qualified name of my assembly at runtime, but I was able to get the type using only the class name from the assembly's ExportedTypes. For instance, to get an export type of "ClassName":

var assembly = Assembly.LoadFile(dllPath);
var types = assembly.ExportedTypes;
if(types != null)
{
    var type = types.Where(x => x.Name == "ClassName").FirstOrDefault();
}

If there were multiple types with the identical name of "ClassName" this would only get the first one, but this is a safe solution for the dlls I'm loading.

like image 21
mcmcmc Avatar answered Nov 02 '22 09:11

mcmcmc


You should specify a full namespace of a type, for example:

encryptionAssembly.GetType("My.Namespace.Encryption")

You can know it using t.FullName

like image 11
ILya Avatar answered Nov 02 '22 09:11

ILya


try specifying the full name of the Encryption type (namespace.classname)

like image 5
eyossi Avatar answered Nov 02 '22 08:11

eyossi