I am trying to load an assembly at runtime, and I'm unsure as to why I can't create an instance of a type in the assembly using the static Activator.CreateInstance()
. It works with Assembly.CreateInstance()
.
string assemblyFilename = "MyAssembly.dll";
string assemblyName = "MyAssembly";
string typeName = "MyAssembly.MyType";
FileInfo fileInfo = new FileInfo(assemblyFilename);
This works:
var assembly = Assembly.LoadFrom(assemblyFilename);
Form form = (Form)assembly.CreateInstance(typeName);
But this does NOT work:
Assembly.LoadFrom(assemblyFilename);
Form form = (Form)Activator.CreateInstance(assemblyName, typeName).Unwrap();
FileNotFoundException thrown:
Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified.
EDIT:
In both cases, after the Assembly.LoadFrom()
call, I can see that my assembly has been loaded when I look in AppDomain.CurrentDomain.GetAssemblies()
.
CreateInstance(ActivationContext, String[]) Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data. CreateInstance(Type) Creates an instance of the specified type using that type's parameterless constructor.
The Activator. CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified then the constructor that takes no parameters, that is, the default constructor, is invoked.
A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced. A static constructor runs before an instance constructor.
You can adjust your file with his path
var path = Assembly.GetAssembly(MyType.GetType()).Location;
var thisAssembly= Assembly.LoadFrom(path);
var TypeName = "";
Type type = thisAssembly.GetType(TypeName);
object instance = Activator.CreateInstance(type);
You have to first load the assembly into your current AppDomain:
AppDomain.CurrentDomain.Load(File.ReadAllBytes(assemblyFileName));
EDIT: Does this work?
Form form = (Form)Activator.CreateInstance(Type.GetType(typeName))
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