I want to use a class from a different project in a separate solution in my current project dynamically. I thought the solution is to load the dll into my project. I used the following code to do my task and it worked.
string dllPath = @"the path of my dll";
var DLL = Assembly.LoadFile(dllPath);
foreach (Type type in DLL.GetExportedTypes())
{
if (type.Name == "targetClassName")
{
var c = Activator.CreateInstance(type);
try
{
type.InvokeMember("myMethod", BindingFlags.InvokeMethod, null, c, new object[] { "Params" });
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
break;
}
}
However, my problem now is that I want to unload the dll, which I can't do because there is no unload method in Assembly. The solution I found is that I must use AppDomain to load the assembly and then unload it.
Now here is my main problem. I keep getting FileNotFoundException
. Here is my code:
public class ProxyDomain : MarshalByRefObject
{
public Assembly GetAssembly(string assemblyPath)
{
try
{
return Assembly.LoadFrom(assemblyPath);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
}
private void BuildButton_Click(object sender, EventArgs e)
{
string dllPath = @"DllPath";
string dir = @"directory Path of the dll";
AppDomainSetup domaininfo = new AppDomainSetup();
domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);
Type Domtype = typeof(ProxyDomain);
var value = (ProxyDomain)domain.CreateInstanceAndUnwrap(
Domtype.Assembly.FullName,
Domtype.FullName);
var DLL = value.GetAssembly(dllPath);
// Then use the DLL object as before
}
The last line is making the following exception Could not load file or assembly 'dll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
I have tried the solutions on this link but nothing is working for me...I keep getting the same exception. After that I want to unload the domain, but I can't get through with the first problem of loading the dll. How to fix my code?
EDIT
When I copy the intended dll in the same bin folder of my project, it works. However, I don't want to copy the dll in my project. Is there a way to load it from its path without copying it to my bin folder?