views:

106

answers:

3

The following code fails with a 'Could not load type 'System.Xml.XmlDocument' from assembly' error:

object a = Type.GetType("System.Xml.XmlDocument", true);

I have a reference to System.Xml in which XmlDocument resides.

Any idea what I am doing wrong?

+1  A: 

Use a fully qualified name, since the assembly may not yet have been loaded:

object a = Type.GetType("System.Xml.XmlDocument, System.Xml", true);
Lucero
That fails. The AssemblyQualifiedName property for System.XmlDocument requires more than just comma + System.Xml, perhaps because it is strongly named. You need to use Type.GetType("System.Xml.XmlDocument, System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
stimpy77
+1  A: 

If you need to be able to dynamically load it from a string, this will work, you must specify the fully qualified name because there are possibly multiple versions of this dll in the GAC. Replace the Version=2.0.0.0 with the version you want to load depending on the framework version you are using.

Assembly xmlAssembly = Assembly.Load("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

Once you have loaded the assembly, you can then dynamically create an instance of the class you are after.

object xmlDoc = xmlAssembly.CreateInstance("System.Xml.XmlDocument", false);
Roatin Marth
+1  A: 

You can usually get by just by appending a comma and the assembly name, i.e. "Namespace.Type, Assembly". However, if an assembly is strongly named, as System.Xml.dll is, you need to use the Type.AssemblyQualifiedName property which returns not just "Namespace.Type, Assembly" but also the signature information required to identify the assembly. This works:

var xmlDocType = Type.GetType("System.Xml.XmlDocument, System.Xml, "
    + "Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
stimpy77
-1: I don't see how this differs from the accepted answer.
John Saunders
With my answer, you're still just using Type.GetType and assuming that the assembly is already referenced. And FYI I just had the *exact* same problem, and the accepted answer was not my solution. This was.
stimpy77